微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

我试图了解它是如何工作的:
1> func returnNone() -> String? { return .None }
  2> returnNone() == nil
$R0: Bool = true
  3> returnNone() == .None
$R1: Bool = true

为什么.None等于零.

在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: ())
}
enum可选符合NilLiteralConvertible协议,
这意味着它可以用“nil”文字初始化.
结果是Optional< T> .None,其中类型占位符T
必须从上下文中推断出来.

举个例子,

let n = nil // type of expression is ambiguous without more context

不编译,但是

let n : Int? = nil

是的,结果是可选< Int> .None.

现在,如果底层证券,通常不会比较期权
type不是Equatable:

struct ABC { }

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

if a1 == a2 { } // binary operator '==' cannot be applied to two 'ABC?' operands

甚至这不编译:

if a1 == Optional<ABC>.None { } // binary operator '==' cannot be applied to two 'ABC?' operands

但这编译:

if a1 == nil { }

它使用运算符

public func ==<T>(lhs: T?,rhs: _OptionalNilComparisonType) -> Bool

其中_OptionalNilComparisonType未正式记录.
https://github.com/andelf/Defines-Swift/blob/master/Swift.swift
定义可以找到(由@rinTaro和@Arsen找到,见评论):

struct _OptionalNilComparisonType : NilLiteralConvertible {
  init(nilLiteral: ())
}

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

简而言之 – 在Optional的上下文中,nil可以被认为是.None的快捷方式,但具体类型必须从上下文中推断出来.有一个专用的==运算符用于与“nil”进行比较.

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐