学习Swift -- 可选链

可空链式调用

可空链式调用是一种可以请求和调用属性、方法及下标的过程,它的可空性体现于请求或调用的目标当前可能为空(nil)。如果可空的目标有值,那么调用就会成功;如果选择的目标为空(nil),那么这种调用将返回空(nil)。多个连续的调用可以被链接在一起形成一个调用链,如果其中任何一个节点为空(nil)将导致整个链调用失败。

使用可空链式调用来强制展开

通过在想调用非空的属性、方法、或下标的可空值后面放一个问号,可以定义一个可空链。这一点很像在可空值后面放一个叹号(!)来强制展开其中值。它们的主要的区别在于当可空值为空时可空链式只是调用失败,然而强制展开将会触发运行时错误。

为了反映可空链式调用可以在空对象(nil)上调用,不论这个调用的属性、方法、下标等返回的值是不是可空值,它的返回结果都是一个可空值。你可以利用这个返回值来判断你的可空链式调用是否调用成功,如果调用有返回值则说明调用成功,返回nil则说明调用失败。

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

下面是运行时错误的例子:

class Residence {
var numberOfRooms = 1
} class Person {
var residence: Residence?
} let john = Person() // 下面这行代码会报错,因为john的residence是可空的,john被初始化后也没有对residence赋值,随意residence为nil
// john.residence! 会强制展开,residence又是空(nil),所以会造成运行时错误
let roomCount = john.residence!.numberOfRooms

下面是安全的写法:

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

为可空链式调用定义模型类

通过使用可空链式调用可以调用多层属性,方法,和下标。这样可以通过各种模型向下访问各种子属性。并且判断能否访问子属性的属性,方法或下标。

person类保持不变:

class Person {
var residence: Residence?
}

Residence类比之前复杂些,增加了一个Room类型的空数组room

class Residence {
var rooms = [Room]()
var numberOfRooms: Int {
return rooms.count
}
subscript (index: Int) -> Room {
get {
return rooms[index]
}
set {
rooms[index] = newValue
}
}
func printNumberOfRooms() {
print("The number of rooms is \(numberOfRooms)")
}
var address: Address?
}

Room是一个简单类,只包含一个属性name,以及一个初始化函数:

class Room {
let name: String
init(name: String){
self.name = name
}
}

最后一个类是Address,这个类有三个String?类型的可空属性。buildingName以及buildingNumber属性表示建筑的名称和号码,用来表示某个特定的建筑。第三个属性表示建筑所在街道的名称:

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 {
print("John's residence has \(roomCount) room(s).")
} else {
print("Unable to retrieve the number of rooms.") // 打印这一行
} let someAddress = Address()
someAddress.buildingNumber = "29"
someAddress.buildingName = "Acacia Road"
john.residence?.address = someAddress
// 因为john的residence属性还是空,所以就算现在设置address也不会成功
print(john.residence?.address?.buildingName) // nil

通过可空链式调用来调用方法

先看眼这个方法:

func printNumberOfRooms() {
print("The number of rooms is \(numberOfRooms)")
}

注意:这个方法没有返回值。但是没有返回值的方法隐式返回Void类型,这意味着没有返回值的方法也会返回()或者空的元组。

如果在可空值上通过可空链式调用来调用这个方法,这个方法的返回类型为Void?,而不是Void,因为通过可空链式调用得到的返回值都是可空的。

这样我们就可以使用if语句来判断能否成功调用printNumberOfRooms()方法,即使方法本身没有定义返回值。通过返回值是否为nil可以判断调用是否成功:

let john = Person()
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中的address属性赋值,即使residencenil。通过可空链式调用给属性赋值会返回Void?。

通过判断返回值是否为nil可以知道赋值是否成功:

let john = Person()

let someAddress = Address()
someAddress.buildingNumber = "29"
someAddress.street = "Acacia Road"
john.residence?.address = someAddress if (john.residence?.address = someAddress) != nil {
print("It was possible to set the address.")
} else {
print("It was not possible to set the address.")  // 调用这一行
}

通过可空链式调用来访问下标

通过可空链式调用,我们可以用下标来对可空值进行读取或写入,并且判断下标调用是否成功。

注意: 当通过可空链式调用访问可空值的下标的时候,应该将问号放在下标方括号的前面而不是后面。可空链式调用的问号一般直接跟在可空表达式的后面。

let john = Person()

if let firstRoomName = john.residence?[0].name {
print("The first room name is \(firstRoomName).")
} else {
print("Unable to retrieve the first room name.")
}
// 打印: "Unable to retrieve the first room name."
// 因为 john的residence属性是空,所以访问其下标肯定会返回空(nil) // 当然 也可以通过可空链赋值,不过下面的代码会赋值失败,如果residence有值的话会成功
john.residence?[0] = Room(name: "room1")

下面看一个成功的例子:

let john = Person()

let house = Residence()
house.rooms.append(Room(name: "Living Room"))
house.rooms.append(Room(name: "Kitchen"))
john.residence = house // 赋值residence属性 现在该属性有值了,不再是nil了
if let firstRoomName = john.residence?[0].name {
print("The first room name is \(firstRoomName).")
} else {
print("Unable to retrieve the first room name.")
}
// 打印出:The first room name is Living Room.

访问可空类型的下标

如果下标返回可空类型值,比如Swift中Dictionarykey下标。可以在下标的闭合括号后面放一个问号来链接下标的可空返回值:

var testScores = ["Dave" : [86, 82, 84], "Bev" : [79, 95, 81]]
testScores["Dave"]?[0] = 91
testScores["Bev"]?[0] += 1
if (testScores["Brian"]?[0] = 99) != nil {
print("Brian's scores is \(testScores["Brian"])")
} else {
print("haven't Brian")
}
// 打印:"haven't Brian"
print("Dave's scores is \(testScores["Dave"]), Bev's scores is \(testScores["Bev"])")
// 打印:"Dave's scores is Optional([91, 82, 84]), Bev's scores is Optional([80, 95, 81])"

多层链接

可以通过多个链接多个可空链式调用来向下访问属性,方法以及下标。但是多层可空链式调用不会添加返回值的可空性。

也就是说:

  • 如果你访问的值不是可空的,通过可空链式调用将会放回可空值。
  • 如果你访问的值已经是可空的,通过可空链式调用不会变得“更”可空,它还是可空的

因此:

  • 通过可空链式调用访问一个Int值,将会返回Int?,不过进行了多少次可空链式调用。
  • 类似的,通过可空链式调用访问Int?值,并不会变得更加可空,它还是Int?类型
let john = Person()

let house = Residence()
house.rooms.append(Room(name: "Living Room"))
house.rooms.append(Room(name: "Kitchen"))
john.residence = house
if let street = john.residence?.address?.street {
print("John's street name is \(street).")
} else {
print("Unable to retrieve the address.")
}
// 打印出:"Unable to retrieve the address."

下面是成功的例子:

let john = Person()

let house = Residence()
house.rooms.append(Room(name: "Living Room"))
house.rooms.append(Room(name: "Kitchen"))
john.residence = house let address = Address()
address.buildingName = "The Larches"
address.street = "Laurel Street"
john.residence?.address = address
if let street = john.residence?.address?.street {
print("John's street name is \(street).")
} else {
print("Unable to retrieve the address.")
}
// 打印:"John's street name is Laurel Street."

对返回可空值的函数进行链接

可以通过可空链式调用来调用返回可空值的方法,并且可以继续对可空值进行链接。

let john = Person()

let house = Residence()
house.rooms.append(Room(name: "Living Room"))
house.rooms.append(Room(name: "Kitchen"))
john.residence = house // 赋值residence属性 现在该属性有值了,不再是nil了 let address = Address()
address.buildingName = "The Larches"
address.street = "Laurel Street"
john.residence?.address = address if let identifier = john.residence?.address?.buildingIdentifier() {
print("John's building identifier is \(identifier).")
} // 通过可选链进一步访问 因为buildingIdentifier()返回的是String?,所以在buildingIdentifier()后要加?
if let beginWithThe = john.residence?.address?.buildingIdentifier()?.hasPrefix("The") {
print("John's building identifier begins with \"The\".")
} else {
print("John's building identifier does not begin with \"The\".")
}
// 打印: "John's building identifier begins with "The"."
上一篇:组装数据- 对象里面是key:value, value里面是数组的形式,如 {key:[aa,bb], key:[cc,dd]}


下一篇:使用vue+iview实现上传文件及常用的下载文件的方法