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 的变量的可选绑定
基础教程推荐
- 在 gmail 中为 ios 应用程序检索朋友的朋友 2022-01-01
- Kivy Buildozer 无法构建 apk,命令失败:./distribute.sh -m “kivy"d 2022-01-01
- 如何在没有IB的情况下将2个按钮添加到右侧的UINavigationbar? 2022-01-01
- 当从同一个组件调用时,两个 IBAction 触发的顺序是什么? 2022-01-01
- android 应用程序已发布,但在 google play 中找不到 2022-01-01
- Android:对话框关闭而不调用关闭 2022-01-01
- 如何在 UIImageView 中异步加载图像? 2022-01-01
- UIWebView 委托方法 shouldStartLoadWithRequest:在 WKWebView 中等效? 2022-01-01
- 如何在 iPhone 上显示来自 API 的 HTML 文本? 2022-01-01
- 如何让对象对 Cocos2D 中的触摸做出反应? 2022-01-01