对照Java学习Swift--可选链式调用(Optional Chaining)

来源:互联网 发布:c语言找出数组最多的数 编辑:程序博客网 时间:2024/05/01 22:06

可选链式调用(Optional Chaining)是一种可以在当前值可能为nil的可选值上请求和调用属性、方法及下标的方法。如果可选值有值,那么调用就会成功;如果可选值是nil,那么调用将返回nil。多个调用可以连接在一起形成一个调用链,如果其中任何一个节点为nil,整个调用链都会失败,即返回nil。

swift这个功能设计的很好,不会报空指针异常,如果是在Java中,那个环节的对象为空,则报空指针异常,程序异常退出,swift则不会,会直接返回一个nil,很方便。

通过在想调用的属性、方法、或下标的可选值(optional value)后面放一个问号(?),可以定义一个可选链。

if let roomCount = john.residence?.numberOfRooms {    print("John's residence has \(roomCount) room(s).")} else {    print("Unable to retrieve the number of rooms.")}

即使residence为nil也不会报异常,会进入else的分支,很简单了。

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

let someAddress = Address()someAddress.buildingNumber = "29"someAddress.street = "Acacia Road"john.residence?.address = someAddress

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

if john.residence?.printNumberOfRooms() != nil {    print("It was possible to print the number of rooms.")} else {    print("It was not possible to print the number of rooms.")}

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

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

访问可选类型的下标

var testScores = ["Dave": [86, 82, 84], "Bev": [79, 94, 81]]testScores["Dave"]?[0] = 91testScores["Bev"]?[0]++testScores["Brian"]?[0] = 72

连接多层可选链式调用

可以通过连接多个可选链式调用在更深的模型层级中访问属性、方法以及下标。然而,多层可选链式调用不会增加返回值的可选层级。

也就是说:

  • 如果你访问的值不是可选的,可选链式调用将会返回可选值。
  • 果你访问的值就是可选的,可选链式调用不会让可选返回值变得“更可选”。

在方法的可选返回值上进行可选链式调用

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\".")        }}
0 0
原创粉丝点击