可选类型、隐式可选类型
在Swift 中可选类型是一个枚举类型(Enum),里面有None和非None两种类型,nil对应于Optional.None;非nil对应于Optional.Some(Wrapped),通过Some(Wrapped) 包装原始值,这也是为什么在使用Optional的时候要拆包(从Enum中的Some取出原始值)的原因,同理在PlayGround中会把Optional值显示为类似{Some”Hello World”},以下是Enum Optional的定义1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16public 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!)`.
@rethrows public func map<U>(@noescape f: (Wrapped) throws -> U) rethrows -> U?
/// Returns `nil` if `self` is nil, `f(self!)` otherwise.
@rethrows public func flatMap<U>(@noescape f: (Wrapped) throws -> U?) rethrows -> U?
/// Create an instance initialized with `nil`.
public init(nilLiteral: ())
}