可選鏈(Optional Chaining)
可選項(xiàng)包裝
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伊诵,不會(huì)調(diào)用getName()
person?.name = getName()
- 如果可選項(xiàng)為nil单绑,調(diào)用方法、下標(biāo)曹宴、屬性失敗搂橙,結(jié)果為nil
- 如果可選項(xiàng)不為nil,調(diào)用方法笛坦、下標(biāo)区转、屬性成功,結(jié)果會(huì)被包裝成可選項(xiàng)
- 如果結(jié)果本來就是可選項(xiàng)版扩,不會(huì)進(jìn)行再次包裝
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é):
多個(gè)?可以鏈接在一起
如果鏈中任何一個(gè)節(jié)點(diǎn)是nil废离,那么整個(gè)鏈就會(huì)調(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?