加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-14 02:24:21 所属栏目:百科 来源:网络整理
导读:我试图了解它是如何工作的: 1 func returnNone() - String? { return .None } 2 returnNone() == nil$R0: Bool = true 3 returnNone() == .None$R1: Bool = true 为什么.None等于零. 在enum定义中我没有看到任何关于它的内容: public enum OptionalWrapped
我试图了解它是如何工作的:
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”进行比较.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读