[iOS笔记]Swift中的可选链式调用的注意点

通过可选链式调用访问属性

下面代码中的赋值过程是可选链式调用的一部分,这意味着可选链式调用失败时,等号右侧的代码不会被执行.

john.residence?.address = createAddress()

注意:
以后如果遇到等式右边的方法一直未执行时, 可以检查等式左侧变量是否有效

通过可选链式调用调用方法

如果通过可选链式调用来调用无返回值的方法,该方法的返回类型会是 Void? ,而不是 Void ,因为通过可选链式调用得到的返回值都是可选的。
这样我们就可以使用 if 语句来判断能否成功调用方法,即使方法本身没有定义返回值。通过判断返回值是否为 nil 可以判断调用是否成功:

 if objectA.objectB?.noReturnMethod() != nil {
    print("It was possible to call method")
 } else { 
    print("It was not possible to call method.")
}
// 打印 “It was not possible to call method.”

通过可选链式调用访问下标

通过可选链式调用,我们可以在一个可选值上访问下标,并且判断下标调用是否成功;
通过可选链式调用访问可选值的下标时,应该将问号放在下标方括号的前面而不是后面

john.residence?[0] = Room(name: "Bathroom")

这次赋值可能会失败,因为 residence 可能是 nil

连接多层可选链式调用

  • 通过可选链式调用访问一个 Int 值,将会返回 Int? ,无论使用了多少层可选链式调用;
  • 类似的,通过可选链式调用访问 Int? 值,依旧会返回 Int? 值,并不会返回 Int??
 if let beginsWithThe = john.residence?.address?.buildingIdentifier()?.hasPrefix("The") {
         if beginsWithThe {
             print("John's building identifier begins with \"The\".")
         } else {
             print("John's building identifier does not begin with \"The\".")
    }
} else {
     print("chaining on methods with optional return values error!")
}
// 打印 “John's building identifier begins with "The".”

上面代码中链式调用返回一个 Bool? 类型, 使用 if let (可选绑定) 将有效值赋值给常量 beginsWithThe, 然后再判断 Bool 是否为 true, 所以需要两层 if 嵌套.

资料:

The Swift Programming Language 中文版

你可能感兴趣的:([iOS笔记]Swift中的可选链式调用的注意点)