Swift increment Int! not working

半腔热情 提交于 2020-01-24 03:24:26

问题


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.


回答1:


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 an Int!:

let num: Int! = 0
let num2 = num // is inferred to be of type 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

Sidenote:

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.




回答2:


You are using wrong type Int!, use Int instead



来源:https://stackoverflow.com/questions/31763467/swift-increment-int-not-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!