无法赋值:'i'是swift中的'let'常量

时间:2015-10-19 16:44:17

标签: ios swift

所以基本上我试图在2个标签中分配2个随机数,最多20个,用户必须找到正确的结果。如果答案是否正确,将出现不同的视图,这将发生10次。 问题是我在我使用的计数器“i”上出现错误,即使我将其声明为变量,我也会收到一个错误,说它是一个常量。

@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)
        }
    }
}

1 个答案:

答案 0 :(得分:22)

使用for var i in 0..<10 {克服错误。

i中的for i in 1..<10实际上是i范围内for的重新声明,默认为let并覆盖您之前的声明。不知道你的逻辑在做什么,介意,在循环中间递增i。循环执行的次数没有区别 - 见下文:

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
*/

重要的是,Swift for i in循环 C for (i=0; i<10; i++)循环。