Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
708 views
in Technique[技术] by (71.8m points)

ios - Cannot assign to value: 'i' is a 'let' constant in swift

So basically i am trying to assign 2 random numbers up to 20 in 2 labels and the user will have to find the correct result. A different view will appear based on if 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 even though I declare it as variable, I get an error saying 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)
        }
    }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

The i in for i in 1..<10 is effectively a redeclaration of i in the for scope, which defaults to let and overrides your previous declaration. No idea what your logic is doing, mind, incrementing i in the middle of the loop. It will make no difference to the number of times the loop is executed - 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 a Swift for i in loop is not a C for (i=0; i<10; i++) loop.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...