Skip to main content

iOS 15 Programming Fundamentals with SwiftのI-3とI-4を読んだので不明点をまとめる

I. Languageの
3. Variables and Simple Types
4. Object Types
で不明点をまとめる


・Pair

let(ix, s)=(1, "two")

let hello = "hello"
for (ix, c) in hello.enumerated() {
    print("character \(ix) is \(c)")
}

let pair = (1, "one")
print(pair.0)

 

・Optional

let num: Int? = 2
if num != nil && num!<3 {
    print(num!)
}

 

・subscript
a[i]
の[]のところ

 

・Enum

enum Filter {
    case album
    case playlists
    case podcasts
    case books
}
let type = Filter.album
let type2 : Filter = .album

 

・Struct
Java脳だと基本的にclassを使うと思うだけど
Swiftになったら基本的にstruct型を使おう
https://software.small-desk.com/development/2021/05/10/which-should-be-used-struct-or-class/

 

・ポリモーフィズム

class Dog {}
class NoisyDog : Dog {
    func beQuiet() {
        print("wow")
    }
}
let d = Dog()

func tellToHush(_ d:Dog) {
    let dog = d  as? NoisyDog
    dog?.beQuiet()
    
    (d as? NoisyDog)?.beQuiet()
}
tellToHush(d)

 

・associatedtype

protocol Flier  {
    func fly()
}
protocol Flocker {
    associatedtype T: Flier
    func flockTogetherWith(f:T)
}
struct Bee : Flier {
    func fly() {}
}
struct Bird : Flocker {
    func flockTogetherWith(f: Bee) {
    }
}

 

・Extention

extension CGRect {
    var center : CGPoint {
        return CGPoint(x:self.midX, y:self.midY)
    }
}

 

・Dictionary

var d2 = [String:String]()
var d3 : [String:String] = [:]

関連記事:

Pocket