中國的孔乙己知道茴香豆的九種寫法,一位老外知道optional的九種拆包方法北启,看看你了解幾種卜朗,哈哈。
茴香豆 VS optional
let optional: Int? = 4
1咕村、if let
if let unwrapped = optional {
print(unwrapped)
}
2场钉、forced unwrapping
print(optional!)
3、guard let
guard var globalUnwrapped = optional else {
return nil
}
print(globalUnwrapped)
4懈涛、pattern matching
if case let unwrapped = optional {
print(unwrapped)
}
5逛万、unsafeUnwrap
print(unsafeUnwrap(optional))
6、map
optional.map{ print($0) }
7批钠、implicitly unwrapped optional cast
print(optional as Int!)
8宇植、optional chaining
optional?.description
9、nil coalescing
print(optional ?? 0)
原文地址: