Comment on page
08.Optional实质
我们先看看
Swift
中Optional
是怎么实现的把public enum Optional<Wrapped> : _Reflectable, NilLiteralConvertible {
case None
case Some(Wrapped)
/// Construct a `nil` instance.
public init()
/// Construct a non-`nil` instance that stores `some`.
public init(_ some: Wrapped)
/// If `self == nil`, returns `nil`. Otherwise, returns `f(self!)`.
@warn_unused_result
public func map<U>(@noescape f: (Wrapped) throws -> U) rethrows -> U?
/// Returns `nil` if `self` is `nil`, `f(self!)` otherwise.
@warn_unused_result
public func flatMap<U>(@noescape f: (Wrapped) throws -> U?) rethrows -> U?
/// Create an instance initialized with `nil`.
public init(nilLiteral: ())
}
很明显可以看出,它实际是一个枚举。
.Some
的关联值就是我们解包出来的在我们对一个
Optional
的变量进行赋值的时候,我们实际上是将初始值放到.Some
中,取值是则是从.Some
中取出。!
- 强制解包,告诉系统这个变量不为
nil
且.Some
中一定有值 - 如果为空则会崩溃
?
- 解包时会先判断是否为
nil
如果不为空则正常解包,否则会返回nil
即默认初始值
Last modified 2yr ago