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.