Ian Newson Ian Newson - 4 months ago 165
Swift Question

Swift for in loop: use var get warning to use let, use let get error

I have the following code in a swift file:

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
in the
loop, which is:

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

However when I change
I get the following error:

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

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


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

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