Swift可选类型:.None == nil如何工作

时间:2022-09-11 18:39:32

I'm trying to understand how does it work:

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

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

Why .None is equal nil.

为什么.None等于零。

I don't see anything about it in enum definition:

在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: ())
}

1 个解决方案

#1


12  

enum Optional conforms to the NilLiteralConvertible protocol, which means that it can be initialized with the "nil" literal. The result is Optional<T>.None where the type placeholder T must be inferred from the context.

enum可选符合NilLiteralConvertible协议,这意味着它可以使用“nil”文字进行初始化。结果是Optional .None,其中必须从上下文中推断类型占位符T.

As an example,

举个例子,

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

does not compile, but

不编译,但是

let n : Int? = nil

does, and the result is Optional<Int>.None.

是的,结果是Optional .None。

Now optionals can in general not be compared if the underlying type is not Equatable:

现在,如果底层类型不是Equatable,则通常不能比较选项:

struct ABC { }

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

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

and even this does not compile:

甚至这不编译:

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

But this compiles:

但这编译:

if a1 == nil { } 

It uses the operator

它使用运算符

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

where _OptionalNilComparisonType is not documented officially. In https://github.com/andelf/Defines-Swift/blob/master/Swift.swift the definition can be found as (found by @rintaro and @Arsen, see comments):

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

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

This allows the comparison of any optional type with "nil", regardless of whether the underlying type is Equatable or not.

这允许将任何可选类型与“nil”进行比较,而不管底层类型是否为Equatable。

In short – in the context of Optionalnil can be thought of as a shortcut to .None, but the concrete type must be inferred from the context. There is a dedicated == operator for comparison with "nil".

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

#1


12  

enum Optional conforms to the NilLiteralConvertible protocol, which means that it can be initialized with the "nil" literal. The result is Optional<T>.None where the type placeholder T must be inferred from the context.

enum可选符合NilLiteralConvertible协议,这意味着它可以使用“nil”文字进行初始化。结果是Optional .None,其中必须从上下文中推断类型占位符T.

As an example,

举个例子,

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

does not compile, but

不编译,但是

let n : Int? = nil

does, and the result is Optional<Int>.None.

是的,结果是Optional .None。

Now optionals can in general not be compared if the underlying type is not Equatable:

现在,如果底层类型不是Equatable,则通常不能比较选项:

struct ABC { }

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

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

and even this does not compile:

甚至这不编译:

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

But this compiles:

但这编译:

if a1 == nil { } 

It uses the operator

它使用运算符

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

where _OptionalNilComparisonType is not documented officially. In https://github.com/andelf/Defines-Swift/blob/master/Swift.swift the definition can be found as (found by @rintaro and @Arsen, see comments):

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

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

This allows the comparison of any optional type with "nil", regardless of whether the underlying type is Equatable or not.

这允许将任何可选类型与“nil”进行比较,而不管底层类型是否为Equatable。

In short – in the context of Optionalnil can be thought of as a shortcut to .None, but the concrete type must be inferred from the context. There is a dedicated == operator for comparison with "nil".

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