Parameters Values: Default or Optional

When we design function or API, have to choose parameters default values. Here are 3 common styles.

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
enum UserType: String {
case Weixin = "wechat"
case Weibo = "weibo"
case QQ = "qq"
}

// 1. Like NSLayoutAnchor, call function can be like less input parameters
func testDefaultParametersValue(userType: UserType = .Weibo) {
print(userType)
}


testDefaultParametersValue()
testDefaultParametersValue(.QQ)

// 2. All parameters have to input
func testOptionalParametersValue(var userType: UserType?) {
// Can set default value inside too
if userType == nil {
userType = .Weibo
}

print(userType)
}

testOptionalParametersValue(nil)
testOptionalParametersValue(.Weixin)


// 3. Like Kingfisher can less parameters or pass nil
func testAll(id: Int? = nil, city: String) {
print(id)
print(city)
}

testAll(city: "Shanghai")
testAll(nil, city: "Shanghai")
testAll(12, city: "Shanghai")