我试图更新未知类型的复杂Dictionary
中的值,因为它同时包含String
s和子字典。我的初始化功能代码如下。
这就是我的Dictionary
以前的样子:
var methods = [
"PUN": [
"name": "Time of PUN",
"params": ["FJ": 18, "IS": 17]
],
"KHR": [
"name": "Time KHR",
"params": ["FJ": 15, "IS": 15]
],
"LHR": [
"name": "Time of LHR",
"params": ["FJ": 19.5, "IS": 17.5 , "MG": 8.9]
]
]
这就是我想要实现的,动态的:
var methods = [
"PUN": [
"name": "Time of PUN",
"params": ["FJ": 18, "IS": 17, "Offset": "0 min", "Midnight": "Standard"]
],
"KHR": [
"name": "Time KHR",
"params": ["FJ": 15, "IS": 15, "Offset": "0 min", "Midnight": "Standard"]
],
"LHR": [
"name": "Time of LHR",
"params": ["FJ": 19.5, "IS": 17.5 , "MG":8.9, "Offset": "0 min", "Midnight": "Standard"]
]
]
这是我的代码:
我从
defaultParams
(Dictionary
)中获取额外值并插入到methods
(Dictionary
)。var methods = [String: AnyObject]()
let defaultParams = ["Offset": "0 min", "Midnight": "Standard"]
init() {
methods["Punjab"] = [
"name": "Punjab Time",
"params": ["FJ": 18, "IS": 17]
]
methods["Karachi"] = [
"name": "Time of Karachi",
"params": ["FJ": 15, "IS": 15]
]
methods["Lahore"] = [
"name": "Lahore City Time",
"params": ["FJ": 19.5, "IS": 17.5 , "MG": 8.9]
]
for (methodName, methodValue) in methods {
var params = methodValue["params"]!!
for (defaultParamKey, defaultParamValue) in defaultParams {
if params.objectForKey(defaultParamKey) == nil {
// I am having problem with the line below, it says
// cannot asign a value of type String to a value of type AnyObject?!
params[defaultParamKey] = defaultParamValue
}
}
}
}
初始化时,我只想用变量
methods
检查字典变量defaultParams
中缺少的值。 最佳答案
这有点复杂,但它起作用:
class Test {
var methods = [String: [String: AnyObject]]()
let defaultParams = ["Offset": "0 min", "Midnight": "Standard"]
init() {
methods["Punjab"] = [
"name": "Punjab Time",
"params": ["FJ": 18, "IS": 17]
]
methods["Karachi"] = [
"name": "Time of Karachi",
"params": ["FJ": 15, "IS": 15]
]
methods["Lahore"] = [
"name": "Lahore City Time",
"params": ["FJ": 19.5, "IS": 17.5 , "MG": 8.9]
]
for (methodName, methodValue) in methods {
for (mKey, mValue) in methodValue {
if mKey == "params" {
var pDic = mValue as! [String: AnyObject]
for (defaultKey, defaultValue) in defaultParams {
if !contains(pDic.keys, defaultKey) {
pDic[defaultKey] = defaultValue
methods[methodName]!["params"]! = pDic
}
}
}
}
}
}
}
let t = Test()
println(t.methods)
结果:
[卡拉奇:[参数:{
Fj=15;
等于15;
午夜=标准;
offset=“0分钟”;
},name:time of karachi],旁遮普:[params:{
Fj=18;
等于17;
午夜=标准;
offset=“0分钟”;
},name:旁遮普时间],拉合尔:[参数:{
fj=“19.5”;
is=“17.5”;
mg=“8.9”;
午夜=标准;
offset=“0分钟”;
},姓名:拉合尔市时间]]
关于swift - 无法更新嵌套字典的值,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/30986452/