Swift增量Int!不工作 [英] Swift increment Int! not working
问题描述
我了解可选控件的工作原理,但这使我陷入了循环.我有一个名为num
的变量,我想增加它,所以我做了以下事情:
I understand how optionals work, but this is throwing me for a loop. I have a variable called num
and I want to increment it, so I did the following:
var num:Int! = 0
num++ //ERROR - Unary operator ++ cannot be applied to an operand of type Int!
但是出于某种原因,Swift不允许我增加展开的Int
的力,即使它被认为像常规的Int
一样具有在后台无弹力的能力.因此,我尝试了以下方法,并且有效:
But for some reason Swift won't let me increment a force unwrapped Int
, even though it is supposed to be treated like a regular Int
with the capability for nil behind the scenes. So I tried the following, and it worked:
var num:Int! = 0
num = num + 1 //NO ERROR
但是,基于它给我的错误消息,我尝试了以下操作以使增量运算符仍然有效:
However, based on the error message it gave me, I tried the following to make the increment operator still work:
var num:Int! = 0
num!++ //NO ERROR
我的问题是,为什么第二和第三位代码没有中断,但是第一行代码却中断了?另外,由于num
是Int!
,我是否应该像普通的Int
那样对待它?最后,由于Int!
应该被当作常规的Int
对待,因此在第三个示例中我该如何解包呢?谢谢.
My question is why does the first bit of code break, when the second and third bits of code don't? Also, since num
is an Int!
, shouldn't I be able to treat it like a regular Int
? Lastly, since an Int!
is supposed to be treated like a regular Int
, how am I able to unwrap it in the third example? Thanks.
推荐答案
使用所有inout
参数都会发生此错误,应将其视为错误.
This error occurs with all inout
parameters and should be considered a bug.
inout
参数通常的工作方式是调用它们的getter方法一次,并使用setter至少调用一次.在这种情况下,getter返回Int!
:
The usual way how inout
parameters work is that their getter gets called once and their setter at least once. In this case the getter returns an Int!
:
let num: Int! = 0
let num2 = num // is inferred to be of type Int!
因此,getter/setter的签名与功能/运算符所期望的不同.但是,如果编译器将该值分配给Int
或这样传递,则应隐式解开该值:
so the signature of the getter/setter is not the same as the function/operator expects. But the compiler should implicitly unwrap the value if it gets assigned to an Int
or passed like so:
var num3 = 0 // is of type Int
num3 = num // gets automatically unwrapped
// also with functions
func someFunc(i: Int) {}
someFunc(num) // gets automatically unwrapped
旁注:
如果要将Int
传递给参数类型为Int!
的inout
的函数,则会发生几乎相同的错误.但是在这里很明显为什么这在逻辑上不起作用:Int
的设置者从不使用nil
.
Almost the same error occurs if you want to pass an Int
to a function with an inout
parameter of type Int!
. But here it is obvious why this doesn't work (logically): The setter of an Int
never takes a nil
.
这篇关于Swift增量Int!不工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!