Optional binding of nil literal vs. variable that is nil in Swift(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 的变量的可选绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:nil 文字与 Swift 中为 nil 的变量的可选绑定
- 使用自定义动画时在 iOS9 上忽略 edgesForExtendedLayout 2022-01-01
- 想使用ViewPager,无法识别android.support.*? 2022-01-01
- Android - 拆分 Drawable 2022-01-01
- Android viewpager检测滑动超出范围 2022-01-01
- MalformedJsonException:在第1行第1列路径中使用JsonReader.setLenient(True)接受格式错误的JSON 2022-01-01
- android 4中的android RadioButton问题 2022-01-01
- 用 Swift 实现 UITextFieldDelegate 2022-01-01
- 在测试浓缩咖啡时,Android设备不会在屏幕上启动活动 2022-01-01
- Android - 我如何找出用户有多少未读电子邮件? 2022-01-01
- 如何检查发送到 Android 应用程序的 Firebase 消息的传递状态? 2022-01-01