Include variable local variables in variable variables

I have this code I did in a 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 job or a better way to make this work?

+5


source to share


3 answers


You can make it city

mutable by adding var

to its declaration:

for (country, var city) in countries {

      



Unfortunately, changing it will not affect your dictionary countries

, because you get a copy of each sub-dictionary. To do what you want, you will need to loop through the keys countries

and change things from there:

for country in countries.keys {
    if countries[country]!["London"] != nil {
       countries[country]!["London"]! = "Picadilly Circus"
    }
}

      

+15


source


Here's a fix in the spirit of the original code:

    import Foundation

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

    for (country, cities) in countries {
        if cities["London"] != nil {
            countries[country]!["London"] = "Piccadilly Circus"
        }
    }

      



As @Nate Cook pointed out, change the value type countries

directly if you want to. The values country

and cities

* are just temporary copies of the value types obtained from the origin data source countries

that are in the scope of the loop for

. Swift making them value values ​​helps you see it!

Note. I changed the name of the value from city

to cities

to clarify the semantics, since this is a dictionary containing one or more cities.

0


source


It's very simple.

for var (country, city) in countries {
   if city["London"] != nil {
      city["London"] = "Piccadilly Circus" 
   }
}

      

0


source







All Articles