Skip to content

Commit 23b6378

Browse files
committed
可空链式调用定义模型
1 parent a35d918 commit 23b6378

File tree

3 files changed

+78
-1
lines changed

3 files changed

+78
-1
lines changed

Optional Chaining.playground/Contents.swift

Lines changed: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,3 +3,78 @@
33
import UIKit
44

55
var str = "Hello, playground"
6+
7+
// 可空链式调用
8+
9+
// 可空链式调用是一种可以请求和调用属性、方法及下标的过程,它的可空性体现于请求或调用的目标当前可能为空。如果可空的目标有值,那么调用就会成功;如果选择的目标为空,那么这种调用将返回空。多个连续的调用可以被链接在一起形成一个调用链,如果其中任何一个节点为空将会导致整个链调用失败。
10+
11+
12+
// 使用可空链式强调来强制展开
13+
// 通过在想调用非空的属性、方法、或下标的可空值后面放一个问号,可以定义一个可空链。
14+
class Person {
15+
var residence:Residence?
16+
}
17+
18+
class Residence {
19+
var numberOfRooms = 1
20+
}
21+
let john = Person()
22+
23+
// 使用!强制展开这个john的residence属性的numberOfRooms值,会出发运行时错误
24+
//let roomCount = john.residence!.numberOfRooms
25+
26+
// swift 提供了另一种访问numberOfRooms的方法,使用?来代替原来叹号!的位置
27+
if let roomCount = john.residence?.numberOfRooms {
28+
print("\(roomCount)")
29+
} else {
30+
print("unable to retrieve the number of rooms.")
31+
}
32+
33+
john.residence = Residence()
34+
35+
36+
// 为可空链式调用定义模型类
37+
// 通过使用可空链式调用可以调用多层属性,方法,和下标。这样可以通过各种模型访问各种子属性。并且判断能否访问子属性的属性,方法或下标
38+
class Residences {
39+
var rooms = [Room]()
40+
var numberOfRooms: Int {
41+
return rooms.count
42+
}
43+
subscript(i:Int) -> Room {
44+
get {
45+
return rooms[i]
46+
}
47+
set {
48+
rooms[i] = newValue
49+
}
50+
}
51+
func printNumberOfRoom() {
52+
print("\(numberOfRooms)")
53+
}
54+
var address:Address?
55+
}
56+
57+
class Address {
58+
59+
}
60+
61+
62+
63+
64+
65+
66+
67+
68+
69+
70+
71+
72+
73+
74+
75+
76+
77+
78+
79+
80+
-263 Bytes
Binary file not shown.
Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,4 @@
11
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
2-
<playground version='5.0' target-platform='ios'/>
2+
<playground version='5.0' target-platform='ios'>
3+
<timeline fileName='timeline.xctimeline'/>
4+
</playground>

0 commit comments

Comments
 (0)