λ³Έλ¬Έ λ°”λ‘œκ°€κΈ°
iOS 🍎/Swift

Swift14 - Optional Chaining

by yongmin.Lee 2021. 2. 3.

Optional Chaining

Optional chaining is a process for querying and calling properties, methods, and subscripts on an optional that might currently be nil. If the optional contains a value, the property, method, or subscript call succeeds; if the optional is nil, the property, method, or subscript call returns nil. Multiple queries can be chained together, and the entire chain fails gracefully if any link in the chain is nil.

 

μ˜΅μ…”λ„ 체이닝

- 맀번 nil ν™•μΈμ„ ν•˜μ§€ μ•Šκ³  μ΅œμ’…μ μœΌλ‘œ μ›ν•˜λŠ” 값이 μžˆλŠ”μ§€ μ—†λŠ”μ§€ 확인할 수 μžˆμŠ΅λ‹ˆλ‹€.

- μ˜΅μ…”λ„ 체이닝은 μ˜΅μ…”λ„μ˜ λ‚΄λΆ€μ˜ λ‚΄λΆ€μ˜ λ‚΄λΆ€λ‘œ μ˜΅μ…”λ„μ΄ μ—°κ²°λ˜μ–΄ μžˆμ„ λ•Œ μœ μš©ν•˜κ²Œ ν™œμš©ν•  수 μžˆμŠ΅λ‹ˆλ‹€.

// μ‚¬λžŒ 클래슀
class Person {
    var name: String
    var job: String?
    var home: Apartment?
    
    init(name: String) {
        self.name = name
    }
}
// μ‚¬λžŒμ΄ μ‚¬λŠ” 집 클래슀
class Apartment {
    var buildingNumber: String
    var roomNumber: String
    var `guard`: Person?
    var owner: Person?
    
    init(dong: String, ho: String) {
        buildingNumber = dong
        roomNumber = ho
    }
}


// μΈμŠ€ν„΄μŠ€ 생성
let yagom: Person? = Person(name: "yagom")
let apart: Apartment? = Apartment(dong: "101", ho: "202")
let superman: Person? = Person(name: "superman")

// μ˜΅μ…”λ„μ²΄μ΄λ‹ μ‚¬μš© x
func guardJob(owner: Person?) {
    if let owner = owner {
        if let home = owner.home {
            if let `guard` = home.guard {
                if let guardJob = `guard`.job {
                    print("μš°λ¦¬μ§‘ κ²½λΉ„μ›μ˜ 직업은 \(guardJob)μž…λ‹ˆλ‹€")
                } else {
                    print("μš°λ¦¬μ§‘ 경비원은 직업이 μ—†μ–΄μš”")
                }
            }
        }
    }
}
guardJob(owner: yagom) // // μš°λ¦¬μ§‘ 경비원은 직업이 μ—†μ–΄μš”

// μ˜΅μ…”λ„μ²΄μ΄λ‹ μ‚¬μš©
func guardJobWithOptionalChaining(owner: Person?) {
    if let guardJob = owner?.home?.guard?.job {
        print("μš°λ¦¬μ§‘ κ²½λΉ„μ›μ˜ 직업은 \(guardJob)μž…λ‹ˆλ‹€")
    } else {
        print("μš°λ¦¬μ§‘ 경비원은 직업이 μ—†μ–΄μš”")
    }
}
yagom?.home?.guard?.job = "μ†Œλ°©κ΄€"
guardJobWithOptionalChaining(owner: yagom) // "μš°λ¦¬μ§‘ κ²½λΉ„μ›μ˜ 직업은 μ†Œλ°©κ΄€μž…λ‹ˆλ‹€"

'iOS 🍎 > Swift' μΉ΄ν…Œκ³ λ¦¬μ˜ λ‹€λ₯Έ κΈ€

Swift16 - νƒ€μž…μΊμŠ€νŒ…  (0) 2021.02.10
Swift15 - Nil-Coalescing Operator  (0) 2021.02.03
Swift13 - Initialization & Deinitialization  (0) 2021.02.02
Swift12 - 상속  (0) 2021.02.02
Swift11 - ν”„λ‘œνΌν‹°  (0) 2021.02.02