无法赋值:'i'是swift中的'let'常量 [英] Cannot assign to value: 'i' is a 'let' constant in swift

查看:409
本文介绍了无法赋值:'i'是swift中的'let'常量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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


推荐答案

在0 ..< 10 {>中使用表示var i来克服错误。

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

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

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

重点是一个Swift for i in loop is not a C for(i = 0; i< 10; i ++) l oop。

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

这篇关于无法赋值:'i'是swift中的'let'常量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆