中国的孔乙己知道茴香豆的九种写法,一位老外知道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)
原文地址: