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!
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
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.
This error occurs with all
inout
parameters and should be considered a bug.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 anInt!
: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:Sidenote:
Almost the same error occurs if you want to pass an
Int
to a function with aninout
parameter of typeInt!
. But here it is obvious why this doesn't work (logically): The setter of anInt
never takes anil
.You are using wrong type
Int!
, useInt
instead