Swift可选类型:如何.None == nil有效

Ars*_*sen 5 optional swift

我试图了解它是如何工作的:

  1> func returnNone() -> String? { return .None }
  2> returnNone() == nil
$R0: Bool = true
  3> returnNone() == .None
$R1: Bool = true
Run Code Online (Sandbox Code Playgroud)

为什么.None是平等的nil.

在enum定义中我没有看到任何关于它的内容:

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
    @rethrows public func map<U>(@noescape f: (Wrapped) throws -> U) rethrows -> U?
    /// Returns `nil` if `self` is nil, `f(self!)` otherwise.
    @warn_unused_result
    @rethrows public func flatMap<U>(@noescape f: (Wrapped) throws -> U?) rethrows -> U?
    /// Create an instance initialized with `nil`.
    public init(nilLiteral: ())
}
Run Code Online (Sandbox Code Playgroud)

Mar*_*n R 12

enum Optional符合NilLiteralConvertible协议,这意味着它可以用"nil"文字初始化.结果是 必须从上下文推断Optional<T>.None类型占位符T.

举个例子,

let n = nil // type of expression is ambiguous without more context
Run Code Online (Sandbox Code Playgroud)

不编译,但是

let n : Int? = nil
Run Code Online (Sandbox Code Playgroud)

是的,结果是Optional<Int>.None.

现在,如果基础类型不是,则通常不会比较选项Equatable:

struct ABC { }

let a1 : ABC? = ABC()
let a2 : ABC? = ABC()

if a1 == a2 { } // binary operator '==' cannot be applied to two 'ABC?' operands
Run Code Online (Sandbox Code Playgroud)

甚至这不编译:

if a1 == Optional<ABC>.None { } // binary operator '==' cannot be applied to two 'ABC?' operands
Run Code Online (Sandbox Code Playgroud)

但这编译:

if a1 == nil { } 
Run Code Online (Sandbox Code Playgroud)

它使用运算符

public func ==<T>(lhs: T?, rhs: _OptionalNilComparisonType) -> Bool
Run Code Online (Sandbox Code Playgroud)

哪里_OptionalNilComparisonType没有正式记录.在https://github.com/andelf/Defines-Swift/blob/master/Swift.swift中可以找到定义(由@rintaro和@Arsen找到,见评论):

struct _OptionalNilComparisonType : NilLiteralConvertible {
  init(nilLiteral: ())
}
Run Code Online (Sandbox Code Playgroud)

这允许将任何可选类型与"nil"进行比较,无论基础类型是否Equatable存在.

简而言之 - 在上下文中Optional- nil可以被认为是一种捷径.None,但具体类型必须从上下文中推断出来.有一个专门的 ==运算符与"nil"进行比较.