Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

turn for in loops local variables into mutable variables

Tags:

swift

I've this code that I made on playground to represent my problem:

import Foundation

var countries = ["Poland":["Warsaw":"foo"],"England":["London":"foo"]]

for (country, city) in countries {
  if city["London"] != nil {
   city["London"] = "Piccadilly Circus" // error because by default the variables [country and city] are constants (let)
  }
} 

Does anyone know a work around or the best way to make this work?

like image 679
Nuno Avatar asked Sep 11 '14 17:09

Nuno


1 Answers

You can make city mutable by adding var to its declaration:

for (country, var city) in countries {

Unfortunately, changing it won't affect your countries Dictionary, because you're getting a copy of each sub-Dictionary. To do what you want, you'll need to loop through the keys of countries and change things from there:

for country in countries.keys {
    if countries[country]!["London"] != nil {
       countries[country]!["London"]! = "Picadilly Circus"
    }
}
like image 122
Nate Cook Avatar answered Sep 20 '22 13:09

Nate Cook