
可选值:
如: let optionValue:Int?
Int和Int?是两种不同的类型
1. 解包
|
|
2. 强制解包 optionValue! ,当有十足的把握确定 optionValue != nil 时,我们可以使用 强制解包
let y = optionValue! + 1
强制解包 容易造成奔溃,不建议使用
- 强制解包的代替方案:
??let y = optionValue ?? 100
当
optionValue != nil时,y = optionValue
当optionValue = nil时,y = 100
3. 可选绑定
|
|
4. 可选值链
|
|
5. 分支上的可选值
6. switch case 分支
|
|
7. guard 分支
|
|
8. flatMap 函数 , 检查一个可选值是否为 nil , 若不是,那么将其传递给参数函数 f, 若是 nil 则结果也是nil。
func flatMap<U>(@noescape f: (Wrapped) throws -> U?) rethrows -> U?
|
|
坚持使用 可选值,能够从根本上杜绝 那些 难以察觉的细微错误。
摘自 《函数式 Swift》




近期评论