Swift可选类型:.None == nil的工作方式 [英] Swift Optional type: how .None == nil works
问题描述
我正试图了解它是如何工作的:
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
为什么.None
等于nil
.
我在枚举定义中什么都没看到:
I don't see anything about it in enum definition:
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 Optional
符合NilLiteralConvertible
协议,
这意味着可以使用"nil"文字对其进行初始化.
结果为Optional<T>.None
,其中类型占位符T
必须从上下文中推断出来.
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.
例如,
let n = nil // type of expression is ambiguous without more context
不编译,但是
let n : Int? = nil
这样做,结果为Optional<Int>.None
.
现在,如果基础
类型不是Equatable
:
Now optionals can in general not be compared if the underlying
type is not 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找到,请参见注释):
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):
struct _OptionalNilComparisonType : NilLiteralConvertible {
init(nilLiteral: ())
}
这允许将任何可选类型与"nil"进行比较,而不管基础类型是否为Equatable
.
This allows the comparison of any optional type with "nil", regardless of whether the underlying type is Equatable
or not.
简而言之–在Optional
的上下文中– nil
可以看作是.None
的快捷方式,但是具体类型必须从上下文中推断出来.有一个专用的==
运算符,用于与"nil"进行比较.
In short – in the context of Optional
– nil
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".
这篇关于Swift可选类型:.None == nil的工作方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!