Fork me on GitHub

以撸代码的形式学习Swift-17:可选链式调用(Optional Chaining)

一种可以在当前值可能为nil的可选值上请求和调用属性、方法及下标的方法

1 使用可选链式调用代替强制展开

可选链式调用的返回结果与原本的返回结果具有相同的类型,但是被包装成了一个可选值。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Person {
var residence: Residence?
}
class Residence {
var numberOfRooms = 1
}
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.")
}
john.residence = Residence()
if let roomCount = john.residence?.numberOfRooms {
print("John's residence has \(roomCount) room(s).")
} else {
print("Unable to retrieve the number of rooms.")
}

2 为可选链式调用定义模型类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
class Person2 {
var residence: Residence2?
}
class Residence2 {
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 buildingName != nil {
return buildingName
} else if buildingNumber != nil && street != nil {
return "\(buildingNumber) \(street)"
} else {
return nil
}
}
}
func createAddress() -> Address {
print("Function was called.")
let someAddress = Address()
someAddress.buildingNumber = "29"
someAddress.street = "Acacia Road"
return someAddress
}

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

1
2
let andy = Person2()
andy.residence?.address = createAddress() // andy.residence结果为nil,可选链式调用失败时,等号右侧的代码不会被执行。

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
if let firstRoomName = andy.residence?[0].name {
print("The first room name is \(firstRoomName).")
} else {
print("Unable to retrieve the first room name.")
}
let andyHouse = Residence2()
andyHouse.rooms.append(Room(name: "Living Room"))
andyHouse.rooms.append(Room(name: "Kitchen"))
andy.residence = andyHouse
if let firstRoomName = andy.residence?[0].name {
print("The first room name is \(firstRoomName).")
} else {
print("Unable to retrieve the first room name.")
}

5 访问可选类型的下标

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

6 连接多层可选链式调用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
if let andyStreet = andy.residence?.address?.street {
print("John's street name is \(andyStreet).")
} else {
print("Unable to retrieve the address.")
}
let andyAddress = Address()
andyAddress.buildingName = "东方明珠"
andyAddress.street = "南京东路100号"
andy.residence?.address = andyAddress
if let andyStreet = andy.residence?.address?.street {
print("John's street name is \(andyStreet).")
} else {
print("Unable to retrieve the address.")
}

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

1
2
3
4
5
6
7
8
9
10
11
if let buildingIdentifier = andy.residence?.address?.buildingIdentifier() {
print("John's building identifier is \(buildingIdentifier).")
}
if let beginsWithThe =
andy.residence?.address?.buildingIdentifier()?.hasPrefix("东") {
if beginsWithThe {
print("John's building identifier begins with \"东\".")
} else {
print("John's building identifier does not begin with \"东\".")
}
}

playground文件在andyRon/LearnSwift

坚持原创技术分享,您的支持将鼓励我继续创作!
  • 本文标题: 以撸代码的形式学习Swift-17:可选链式调用(Optional Chaining)
  • 本文作者: AndyRon
  • 发布时间: 2017年07月05日 - 13:42
  • 最后更新: 2018年10月15日 - 18:37
  • 本文链接: http://andyron.com/2017/swift-17-optional-chaining.html
  • 版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 3.0 许可协议。转载请注明出处!