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?
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.
Neither var nor let is needed in the statement. Type this:
for key in dict.keys {
str += key + ":" + dict[key]!.description + "\n"
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With