Swift 5.1 (15) - 可选链接
2020-04-13 本文已影响0人
沐灵洛
可选链接
可选链接:查询和调用当前可能为nil
的可选项的属性,方法和下标的过程。若当前optional
包含值,则属性,方法或下标调用成功;若optional
是nil
,则属性,方法或下标调用会返回nil
。多个可选链接可以链在一起,如果链中的任何可选链接返回nil
,则整个链都会正常失败。
可选链接作为强制解包的替代方法
可选链接表示:在要调用属性,方法或下标的可选项后放置?
。与可选项后放置!
进行强制解包相似,但主要区别在于使用?
时,当可选项为nil
,链接便会返回nil
,来正常失败;若为!
,可选项为nil
时,强制解包会触发运行时错误。
即使要查询的属性,方法或下标返回的是非可选值,可选链接调用的结果也始终是可选的。
class Person {
var residence: Residence?
}
class Residence {
var numberOfRooms = 1
}
let john = Person()
//`!`方式访问属性
let roomCount = john.residence!.numberOfRooms
//`?`方式访问属性
if let roomCount = john.residence?.numberOfRooms {
print("John's residence has \(roomCount) room(s).")
} else {
print("Unable to retrieve the number of rooms.")
}
定义模型类:
class Person {
var residence: Residence?
}
class Residence {
var rooms = [Room]()
var numberOfRooms: Int {
return rooms.count
}
subscript(i: Int) -> Room {
get {
return rooms[i]
}
set {
rooms[i] = newValue
}
}
func printNumberOfRooms() {
print("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 let buildingNumber = buildingNumber, let street = street {
return "\(buildingNumber) \(street)"
} else if buildingName != nil {
return buildingName
} 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.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.")
}
通过可选链接访问下标
if let firstRoomName = john.residence?[0].name {
print("The first room name is \(firstRoomName).")
} else {
print("Unable to retrieve the first room name.")
}
//赋值
john.residence?[0] = Room(name: "Bathroom")
访问可选类型的下标
var testScores = ["Dave": [86, 82, 84], "Bev": [79, 94, 81]]
testScores["Dave"]?[0] = 91
testScores["Bev"]?[0] += 1
testScores["Brian"]?[0] = 72
//调用后: "Dave" : [91, 82, 84] , "Bev": [80, 94, 81]
多级可选链接
多级可选链接:将多个级别的可选链接链接在一起。采用这种方式访问和调用属性,方法和下标时:
1.返回值不是可选的,也会因为可选链接而成为可选类型。
2.返回值本身是可选的,不会因为可选链接变得更加可选。
if let johnsStreet = john.residence?.address?.street {
print("John's street name is \(johnsStreet).")
} else {
print("Unable to retrieve the address.")
}
可选链接上有optional
类型的返回值的方法
if let buildingIdentifier = john.residence?.address?.buildingIdentifier() {
print("John's building identifier is \(buildingIdentifier).")
}
//方法的可选返回值后继续调用
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\".")
}
}
参考资料:
swift 5.1官方编程指南