Swift   发布时间:2022-03-31  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了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 Opt
我试图了解它是如何工作的:
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
定义可以找到(由@rin@R_257_2301@和@Arsen找到,见评论):

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

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

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

大佬总结

以上是大佬教程为你收集整理的Swift可选类型:如何.None == nil有效全部内容,希望文章能够帮你解决Swift可选类型:如何.None == nil有效所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。