我在操场上制作的这段代码代表了我的问题:
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)
}
}
有没有人知道一项工作或最好的方法来使这项工作?
答案 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
值类型。 country
和cities
*值只是从countries
循环范围中的原始for
数据源派生的临时值类型副本。迅速让它们放任其值实际上可以帮助您看到这一点!
注意:我将值的名称从city
更改为cities
以澄清语义,因为它是包含一个或多个城市的字典。
答案 2 :(得分:0)
这很简单。
for var (country, city) in countries {
if city["London"] != nil {
city["London"] = "Piccadilly Circus"
}
}