小编典典

无法分配值:“ i”是迅速的“ let”常量

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

阅读 274

收藏
2020-07-07

共1个答案

小编典典

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

ifor i in 1..<10实际上是一个重新声明ifor范围,默认为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++)循环。

2020-07-07