swift 可选值 解包
可选值:
如: let optionValue:Int?
Int和Int?是两种不同的类型
-
解包
if optionValue != nil { print('optionValue 有值') } else { print("optionValue 为空") } -
强制解包
optionValue!,当有十足的把握确定optionValue != nil时,我们可以使用 强制解包let y = optionValue! + 1强制解包 容易造成奔溃,不建议使用 -
强制解包的代替方案:
??let y = optionValue ?? 100当
optionValue != nil时,y = optionValue当optionValue = nil时,y = 100 -
可选绑定
if let y = optionValue { print('optionValue 有值') } else { print('optionValue 为空') } -
可选值链
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 -
分支上的可选值
switch case分支
// 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 为 空") }guard分支
let citys = ["广东":"广州","福建":"福州","陕西":"西安"] func provincialCapital(city:String) -> String?{ guard let capital = citys[city] else {retutn nil} return capital } -
flatMap函数 , 检查一个可选值是否为 nil , 若不是,那么将其传递给参数函数 f, 若是 nil 则结果也是nil。func flatMap<U>(@noescape f: (Wrapped) throws -> U?) rethrows -> U?var values:[Int?] = [1,3,5,7,9,nil] let flattenResult = values.flatMap{ $0 } /// [1, 3, 5, 7, 9]
坚持使用 可选值,能够从根本上杜绝 那些 难以察觉的细微错误。
摘自 《函数式 Swift》