Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

swift

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?

like image 501
Ian Newson Avatar asked Sep 01 '16 11:09

Ian Newson


Video Answer


2 Answers

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.

like image 34
Ratso Avatar answered Oct 24 '22 08:10

Ratso


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

for key in dict.keys {
    str += key + ":" + dict[key]!.description + "\n"
}
like image 166
pedrouan Avatar answered Oct 24 '22 08:10

pedrouan