@fiy-fish
2018-01-16T07:48:58.000000Z
字数 1191
阅读 1380
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:Intlet person: Person?}struct Person{let name: Stringlet address: Address?}struct Address {let streetNmae: Stringlet city: Stringlet 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》
