Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to increment Int-typed member variable in Swift

Tags:

ios

swift

I'm writing a Swift app and having trouble incrementing an Int type member variable.

I created the variable with

let index:Int 

then in the initializer I instantiated it using

self.index = 0 

Later, when I try to increment it in a function using either of

self.index++ 

or

self.index = self.index + 1 

I am told in the first case that "Cannot invoke '++' with argument of type 'Int'" and in the second case that "Cannot assign to 'pos' in 'self'".

I haven't been able to find information on the ++ operator, except that you can write custom versions of it, but I'd assume it's at least built in to the integer type. If that's not true then that answers that question.

The other question I have no idea about.

like image 986
NumberOneRobot Avatar asked Nov 28 '14 18:11

NumberOneRobot


People also ask

Can you use ++ in Swift?

Increment and Decrement operatorSwift provides an increment operator ++ and a decrement operator to increase or decrease the value of a numeric variable by 1. The operator with variables of any integer or floating-point type is used. The ++ and -- symbol is used as a prefix operator or postfix operator.

What does ++ mean in Swift?

x++ operator is an operator that is used in multiple languages - C, C++, Java (see the C answer for the same question) It is called post-increment. It increments the given variable by one but after the current expression is evaluated.

How do you increment variables?

The most simple way to increment/decrement a variable is by using the + and - operators. This method allows you increment/decrement the variable by any value you want.


2 Answers

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 initialization then 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 removed in Swift 3 (as mentioned in a comment), so – if declared as a variable – you increment it with

index += 1 

instead.

like image 133
Martin R Avatar answered Sep 23 '22 21:09

Martin R


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.

like image 23
Max Haii Avatar answered Sep 23 '22 21:09

Max Haii