How to increase the value of an Int-typed member variable in Swift

I am writing a Swift application and have difficulty adding a member variable of type Int.

I created a variable with

let index:Int 

then in the initializer I created it using

 self.index = 0 

Later, when I try to increase it in function using any of

 self.index++ 

or

 self.index = self.index + 1 

In the first case, I said that "cannot call" ++ "with an argument of type" Int ", and in the second case," cannot assign "pos" to "I".

I have not been able to find information about the ++ operator, except that you can write your own versions, but I assume that it is at least built into an integer type. If this is not so, then this answers this question.

Another question that I do not know about.

Thanks!

+7
ios swift
source share
2 answers

IN

 class MyClass { let index : Int init() { index = 0 } func foo() { index++ // Not allowed } } 

index is a persistent property. It can be given an initial value

 let index : Int = 0 

and can only be changed during initialization (And it must have a certain value when initialization is completed.)

If you want to change the value after it is initialized, you will have to declare it as a stored property of the variable:

 var index : Int 

See the "Properties" in the Swift documentation for more information.

Please note that ++ and -- are deprecated in Swift 2.2 and removed in Swift 3 (as indicated in the comment), so - if declared as a variable - you increase it with

 index += 1 

instead.

+18
source share

I think you can change

 let index:Int 

in

 var index:Int = 0 

As you increment the index value by CHANGING its value, you need to declare it as var . In addition, you should know that let used to declare a constant.

Then you can use self.index++ . Note that there is no space between self.index and ++ .

Hope this helps.

+2
source share

All Articles