在Swift中nil文字与变量nil的可选绑定

编程入门 行业动态 更新时间:2024-10-07 22:29:07
本文介绍了在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的可选绑定

本文发布于:2023-11-26 23:34:51,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1635666.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:可选   绑定   变量   文字   Swift

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!