How to increment Int-typed member variable in Swift How to increment Int-typed member variable in Swift ios ios

How to increment Int-typed member variable in Swift


In

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

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

let index : Int = 0

and can only be modified during initialization(And it must have a definite value when initialization is finished.)

If you want to change the value after its initializationthen you'll have to declare it as a variable stored property:

var index : Int

More information in "Properties" in the Swift documentation.

Note that the ++ and -- are deprecated in Swift 2.2 and removedin Swift 3 (as mentioned in a comment), so – if declared as a variable –you increment it with

index += 1

instead.


I think you can change

let index:Int

into

var index:Int = 0

Because you are incrementing the value of index, CHANGING its value, you need to declare it as a var. Also, it's worthy of knowing that let is used to declare a constant.

Then, you can use self.index++. Notice that there's no space in between self.index and ++.

Hope this will help.