iOS π/Swift
Swift14 - Optional Chaining
yongmin.Lee
2021. 2. 3. 20:34
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) // "μ°λ¦¬μ§ κ²½λΉμμ μ§μ
μ μλ°©κ΄μ
λλ€"