Swift for in循环:使用var get warning来使用let,使用let get error

时间:2021-03-21 20:57:13

I have the following code in a swift file:

我在swift文件中有以下代码:

func testDictionary(dict :Dictionary<String,AnyObject>) {
    var str = ""
    for var key in dict.keys {
        str += key + ":" + dict[key]!.description + "\n"
    }
    self.alert("Dict", message: str)
}

The above code produces a warning on the user of var in the for loop, which is:

以上代码对for循环中的var用户发出警告:

Variable 'key' was never mutated; consider changing to 'let' constant

However when I change var to let I get the following error:

但是当我改变var让我得到以下错误:

'let' pattern cannot appear nested in an already immutable context

Why do I get a warning when the suggested correction is a compiler error?

当建议的更正是一个编译错误时,为什么会得到警告?

2 个解决方案

#1


21  

Neither var nor let is needed in the statement. Type this:

语句中既不需要var,也不需要let。类型:

for key in dict.keys {
    str += key + ":" + dict[key]!.description + "\n"
}

#2


0  

I think the answer here is that the for-in loop by default provides a key that is already a constant. Therefore using the let keyword is redundant. When you used the var keyword, you were saying you wanted a variable key, but you never change it, therefore you don't need to use var.

我认为这里的答案是forin循环默认地提供了一个已经是常量的键。因此使用let关键字是多余的。当您使用var关键字时,您说您想要一个变量键,但是您从不更改它,因此您不需要使用var。

#1


21  

Neither var nor let is needed in the statement. Type this:

语句中既不需要var,也不需要let。类型:

for key in dict.keys {
    str += key + ":" + dict[key]!.description + "\n"
}

#2


0  

I think the answer here is that the for-in loop by default provides a key that is already a constant. Therefore using the let keyword is redundant. When you used the var keyword, you were saying you wanted a variable key, but you never change it, therefore you don't need to use var.

我认为这里的答案是forin循环默认地提供了一个已经是常量的键。因此使用let关键字是多余的。当您使用var关键字时,您说您想要一个变量键,但是您从不更改它,因此您不需要使用var。