Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.1k views
in Technique[技术] by (71.8m points)

swift - turn for in loops local variables into mutable variables

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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"
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...