可選鏈(Optional Chaining)
class Car { var price = 0 }
class Dog { var weight = 0 }
class Person {
var name: String = ""
var dog: Dog = Dog()
var car: Car? = Car()
func age() -> Int { 18 }
func eat() { print("Person eat") }
subscript(index: Int) -> Int { index }
}
var person: Person? = Person()
var age1 = person!.age() // Int
var age2 = person?.age() // Int?
var name = person?.name // String?
var index = person?[6] // Int?
func getName() -> String { "jack" }
// 如果person是nil躺率,不會調(diào)用getName()
person?.name = getName()
- 如果可選項為nil,調(diào)用方法万矾、下標(biāo)悼吱、屬性失敗,結(jié)果為nil
- 如果可選項不為nil良狈,調(diào)用方法后添、下標(biāo)、屬性成功薪丁,結(jié)果會被包裝成可選項
- 如果結(jié)果本來就是可選項遇西,不會進行再次包裝
if let _ = person?.eat() { // ()?
print("eat調(diào)用成功")
} else {
print("eat調(diào)用失敗")
}
var dog = person?.dog // Dog?
var weight = person?.dog.weight // Int? var price = person?.car?.price // Int?
- 多個?可以鏈接在一起
- 如果鏈中任何一個節(jié)點是nil馅精,那么整個鏈就會調(diào)用失敗
可選鏈
var scores = ["Jack": [86, 82, 84], "Rose": [79, 94, 81]]
scores["Jack"]?[0] = 100
scores["Rose"]?[2] += 10
scores["Kate"]?[0] = 88
var num1: Int? = 5
num1? = 10 // Optional(10)
var num2: Int? = nil
num2? = 10 // nil
var dict: [String : (Int, Int) -> Int] = [
"sum" : (+),
"difference" : (-)
]
var result = dict["sum"]?(10, 20) // Optional(30), Int?