nil 文字与 Swift 中为 nil 的变量的可选绑定 [英] Optional binding of nil literal vs. variable that is nil in Swift

查看:52
本文介绍了nil 文字与 Swift 中为 nil 的变量的可选绑定的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Swift 中,为什么会这样

In Swift, why does

var x: Int? = nil
if let y: Int? = x { ... }

行为不同于

if let y: Int? = nil { ... }

我对第一个案例为什么成功的理解表明第二个案例也应该如此,所以我一定不是真的理解.

My understanding of why the first case succeeds suggests that the second should as well, so I must not really be understanding.

后者不是因为无效分配而失败,也不是因为可选链接;否则它似乎与前者相同.后者为何失败,与前者有何不同.究竟在什么时候,出于什么原因,第二个可选绑定被放弃了?

The latter is not failing because of an invalid assignment, nor because of optional chaining; and otherwise it seems the same as the former. Why does the latter fail, and how is it different from the former. Exactly at what point, and for what reason, is the second optional binding abandoned?

推荐答案

if let y: Int? = nil { ... }

等价于

if let y: Int? = nil as Int?? { ... }

等价于

if let y: Optional<Int> = Optional<Optional<Int>>() { ... }

这会尝试将 Optional<Optional<Int>> 转换为 Optional<Int>,但它失败了,因为 Optional<Optional<Int>>() 不包含 Optional 值.

This tries to cast Optional<Optional<Int>> to Optional<Int>, and it fails because Optional<Optional<Int>>() does not contains Optional<Int> value.

Oneliner 相当于

Oneliner equivalent to

var x: Int? = nil
if let y: Int? = x { ... } 

if let y: Int? = nil as Int? { ... } 

<小时>

添加:

正如我对 Swift 的回答可选绑定到它的参数类型?.

if let y: Int? = nil as Int? { ... }

编译为:

if let y:Int? = nil as Int? as Int?? { ... }

在这里,我们应该注意 nil 作为 Int?as Int?? 等价于 nil as Int??.前者是Optional(Optional<Int>()),而后者是Optional.

Here, we should mind that nil as Int? as Int?? is not equivalent to nil as Int??. The former is Optional(Optional<Int>()), but the latter is Optional<Optional<Int>>().

考虑到这一点,我认为,

With this in mind, I think,

所以我的第一个示例中的可选绑定(确实)检查内部"并找到 nil,这对于分配给 Int 是完全有效的?但是我第二次检查并找到了 Optional(nil),它不能分配给 Int?

So the optional binding in my first example (does indeed) "check inside" and finds nil, which is perfectly valid to assign to Int?; but my second checks and finds Optional(nil), which can't be assigned to Int?

Int?? 的第一个示例检查内部"并找到 Optional 值,即 Int? 类型可以分配给 Int?;但是第二个发现 nothing 被分配并且失败了.

The first example "check inside" of Int?? and just finds Optional<Int>() value that is Int? type which can be assigned to Int?; But the second one finds nothing to be assigned and fails.

这篇关于nil 文字与 Swift 中为 nil 的变量的可选绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆