跳转至

可选链

可选链

可选链是一种可以请求和调用属性、方法及下表脚本的过程。请求或者调用的目标当前可能为nil。如果可选的目标有值,那么调用就会成功;如果选择的目标为nil,则这种调用将返回nil。多次请求或调用可以被链接在一起形成一个链,如果任何一个节点为nil将导致整个链失败。

通过在想调用的属性、方法、或下标脚本的可选值后面放一个问号,可以定义一个可选链。这一点很像在可选值后面放一个叹号来强制拆得其封包内的值。它们的主要的区别在于**当可选值为空时可选链即刻失败,然而一般的强制解析将会引发运行时错误**。

调用可选链的返回结果与原本的返回结果具有相同的类型,但是原本的返回结果被包装成了一个可选值,当可选链调用成功时,一个应该返回Int的属性将会返回Int?

1
2
3
4
5
6
7
class Person {
    var residence: Residence?
}

class Residence {
    var numberOfRooms = 1
}

let john = Person()
使用!强制解析,将会引发运行时错误
1
2
3
4
5
if let roomCount = john.residence!.numberOfRooms{
    println("John's residence has \(roomCount) room(s).")
} else {
    println("Unable to retrieve the number of rooms.")
}

使用可选链

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


john.residence = Residence()

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

class Person {
    var residence: Residence?
}
//住宅
class Residence {
    var rooms = [Room]()
    var numberOfRooms: Int {
        return rooms.count
    }
    subscript(i: Int) -> Room {
        return rooms[i]
    }
    func printNumberOfRooms() {
        println("The number of rooms is \(numberOfRooms)")
    }
    var address: Address?
}
//房间
class Room {
    let name: String
    init(name: String) { self.name = name }
}
// 地址
class Address {
    var buildingName: String?
    var buildingNumber: String?
    var street: String?
    func buildingIdentifier() -> String? {
        if (buildingName != nil) {
            return buildingName
        } else if (buildingNumber != nil) {
            return buildingNumber
        } else {
            return nil
        }
    }
}

let john = Person()
// 调用属性
if let roomCount = john.residence?.numberOfRooms {
    println("John's residence has \(roomCount) room(s).")
} else {
    println("Unable to retrieve the number of rooms.")
}
// 打印 "Unable to retrieve the number of rooms。
//调用方法
// ()等价于Void类型
if let printNumberOfRooms:()=john.residence?.printNumberOfRooms() {
    println("It was possible to print the number of rooms.")
} else {
    println("It was not possible to print the number of rooms.")
}
// 打印It was not possible to print the number of rooms.
//调用可选链脚本
if let firstRoomName = john.residence?[0].name {
    println("The first room name is \(firstRoomName).")
} else {
    println("Unable to retrieve the first room name.")
}
// 打印 "Unable to retrieve the first room name."。

评论