将局部变量转换为可变变量

时间:2014-09-11 17:18:16

标签: swift

我在操场上制作的这段代码代表了我的问题:

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

有没有人知道一项工作或最好的方法来使这项工作?

3 个答案:

答案 0 :(得分:15)

您可以通过在其声明中添加city来使var变为可变:

for (country, var city) in countries {

不幸的是,更改它不会影响您的countries词典,因为您正在获取每个子词典的副本。要做你想做的事,你需要循环遍历countries的键并从那里改变事物:

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

答案 1 :(得分:0)

以下是原始代码精神的修正:

    import Foundation

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

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

正如@Nate Cook所指出的,如果您要这样做,请直接更改countries值类型。 countrycities *值只是从countries循环范围中的原始for数据源派生的临时值类型副本。迅速让它们放任其值实际上可以帮助您看到这一点!

注意:我将值的名称从city更改为cities以澄清语义,因为它是包含一个或多个城市的字典。

答案 2 :(得分:0)

这很简单。

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