问题描述
为什么
如果让y:Int? = nil {...}
相同
如果让y:Int? = nil为Int ?? {...}
(因此无效的分配),特别是当它自己
让y:Int? = nil
与
<$不同p $ p>
让y:Int? = nil为Int ??
(因为让y:Int?= nil
是一个有效的任务)?
考虑可选绑定的用途。它允许你取一个可选值,并判断它是否是 nil
,如果它不是 nil
,打开包含的值并将其绑定到变量。所以它是这样的:
如果让non_optional_var = optional_expr {
...
} else {
...
}
因此如果 optional_expr
的类型为 T?
,然后 non_optional_var
的类型为 T
。 (当我写non_optional_var时,我并不是说它不能是可选的,而是表示它比optional_expr具有更少的可选性级别。因此,如果 non_optional_var
是类型 Int?
,然后 optional_expr
的类型是 Int? ?
。
顺便说一下,可选的绑定语法是用于打开 Optional $ c的语法糖$ c> enum:
switch optional_expr {
case .Some(let non_optional_var):
.. 。
case .None:
...
}
Why is
if let y: Int? = nil { ... }
if let y: Int? = nil as Int?? { ... }
(and thus an invalid assignment) especially when, on its own
let y: Int? = nil
is not the same as
let y: Int? = nil as Int??
(since let y: Int? = nil
is a valid assignment)?
Think about what optional binding is for. It allows you to take an optional value, and condition on whether it is nil
or not, and if it is not nil
, to unwrap the contained value and bind it to a variable. So it is like this:
if let non_optional_var = optional_expr {
...
} else {
...
}
Thus if optional_expr
has type T?
, then non_optional_var
has type T
. (When I wrote "non_optional_var" I didn't mean literally that it can't be optional, but to express that it has one less level of optional-ness than the "optional_expr". Thus, if non_optional_var
is type Int?
, then optional_expr
has type Int??
.
By the way, the optional binding syntax is syntactic sugar for switching on the Optional
enum:
switch optional_expr {
case .Some(let non_optional_var):
...
case .None:
...
}
这篇关于Swift的可选绑定对它的参数类型有什么影响?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!