swift 可选值 解包

可选值:

如: let optionValue:Int?

IntInt? 是两种不同的类型

1. 解包

1
2
3
4
5
if optionValue != nil {
print('optionValue 有值')
} else {
print("optionValue 为空")
}

2. 强制解包 optionValue! ,当有十足的把握确定 optionValue != nil 时,我们可以使用 强制解包

let y = optionValue! + 1
强制解包 容易造成奔溃,不建议使用

  • 强制解包的代替方案:??
    let y = optionValue ?? 100

    optionValue != nil 时, y = optionValue
    optionValue = nil 时,y = 100

3. 可选绑定

1
2
3
4
5
if let y = optionValue {
print('optionValue 有值')
} else {
print('optionValue 为空')
}

4. 可选值链

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
struct Order{
let orderNumber:Int
let person: Person?
}
struct Person{
let name: String
let address: Address?
}
struct Address {
let streetNmae: String
let city: String
let state: String?
}
//显示解包,有可能会奔溃
let state1 = order.person!.address!.state!
//可选链
let state2 = order.person?.address?.state

5. 分支上的可选值

6. switch case 分支

1
2
3
4
5
6
7
// number 是可选值
switch number{
case 0?: print("number 是 0")
case (1..<1000)?: print("number 是 1000 以内的数")
case .Some(let x): print(" number 是 (x)")
case .None: print(" number 为 空")
}

7. guard 分支

1
2
3
4
5
let citys = ["广东":"广州","福建":"福州","陕西":"西安"]
func provincialCapital(city:String) -> String?{
guard let capital = citys[city] else {retutn nil}
return capital
}

8. flatMap 函数 , 检查一个可选值是否为 nil , 若不是,那么将其传递给参数函数 f, 若是 nil 则结果也是nil。

func flatMap<U>(@noescape f: (Wrapped) throws -> U?) rethrows -> U?

1
2
3
var values:[Int?] = [1,3,5,7,9,nil]
let flattenResult = values.flatMap{ $0 }
/// [1, 3, 5, 7, 9]

坚持使用 可选值,能够从根本上杜绝 那些 难以察觉的细微错误。

摘自 《函数式 Swift》