Ian Newson Ian Newson - 3 months ago 115
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
var
in the
for
loop, which is:

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


However when I change
var
to
let
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?

Answer

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

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