Links
Comment on page

08.Optional实质

底层实现

我们先看看SwiftOptional是怎么实现的把
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即默认初始值