可选链(Optional Chaining)

如果可选项为nil,调用方法、下标、属性失败,结果为nil
如果可选项不为nil,调用方法、下标、属性成功,结果会被包装成可选项
如果结果本来就是可选项,不会进行再次包装

  1. class Person {
  2. var name: String = "Jack"
  3. var age: Int = 20
  4. func eat() {
  5. }
  6. }
  7. var p: Person? = Person()
  8. var name = p?.name
  9. var age = p!.age
  10. var eat = p?.eat()
  11. print(name, age, eat) // Optional("Jack") 20 Optional(())

多个?可以链接在一起,如果链中任何一个节点是nil,那么整个链就会调用失败

  1. class Dog {
  2. var weight: Int = 10
  3. }
  4. class Car {
  5. var price = 0
  6. }
  7. class Person {
  8. var car: Car?
  9. var dog: Dog = Dog()
  10. }
  11. var p: Person? = Person()
  12. var dog = p?.dog // Dog?
  13. var weight = p?.dog.weight // Int?
  14. var price = p?.car?.price // Int?

当给可选项赋值时,也可以通过添加?,来实现只有当变量有值时,才能进行赋值

  1. var num1: Int? = 5
  2. num1? = 10 // Optional(10)
  3. var num2: Int? = nil
  4. num2? = 10 // nil