Unable to assign value: "i" is the constant "let" in swift

So basically I'm trying to assign 2 random numbers to 20 in 2 labels, and the user will have to find the correct result. Another view will be displayed, based on whether the answer is correct or not, and this will happen 10 times. The problem is that I get an error on the counter "i" that I use, and although I declare it a variable, I get a message that it is a constant.

@IBAction func submit(sender: AnyObject) { //declarations var i: Int //counter for 10 repetitions var result = 0 for i in 0..<10 { //generate 2 random numbers up to 20 var rn1 = arc4random_uniform(20) var rn2 = arc4random_uniform(20) //assign the rundom numbers to the labels n1.text = String(rn1) n2.text = String(rn2) result = Int((rn1) + (rn2)) //show respective view based on if answer is correct or not if answer.text == String(result) { i = i + 1 //here i get the error: cannot assign to value 'i' is a 'let' constant performSegueWithIdentifier("firstsegue", sender: self) }else { performSegueWithIdentifier("wrong", sender: self) } } } 
+5
source share
1 answer

Use for var i in 0..<10 { to overcome the error.

i in for i in 1..<10 is, in fact, an override of i in the for scope, which by default is let and overrides your previous declaration. Do not imagine what your logic is doing, the mind, increasing i in the middle of the cycle. This will not affect the number of cycles performed by the cycle - see below:

 var i: Int = -1 print("Outer scope, i=\(i)") // i=-1 for var i in 0..<10 { // Will be executed 10 times, regardless of what you do to i in the loop print("Inner scope, i=\(i)") // i=0...9, including all if i == 2 { i = i + 10 print("Inner, modified i=\(i)") // i=12 } } print("Outer scope, i=\(i)") // i=-1 /* Complete output: Outer scope, i=-1 Inner scope, i=0 Inner scope, i=1 Inner scope, i=2 Inner, modified i=12 Inner scope, i=3 Inner scope, i=4 Inner scope, i=5 Inner scope, i=6 Inner scope, i=7 Inner scope, i=8 Inner scope, i=9 Outer scope, i=-1 */ 

The important point is that the Swift for i in loop is not a C for (i=0; i<10; i++) loop for (i=0; i<10; i++) .

+19
source

Source: https://habr.com/ru/post/1234044/


All Articles