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

查看:87
本文介绍了在Swift中nil文字与变量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<Int>值而失败.

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

相当于

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

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


已添加:


ADDED:

当我在回答时,Swift的功能是什么是否对它的参数类型进行了可选绑定?

As I answered on What does Swift's optional binding do to the type it's arguments?.

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

编译为:

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

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

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>>().

考虑到这一点,

因此,第一个示例中的可选绑定(确实)检查了内部"并找到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??的内部检查",只是找到可以分配给Int?Optional<Int>()类型的Optional<Int>()值;但是第二个发现没有要分配,并且失败了.

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.

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

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