无法更新嵌套Dictionary的值

时间:2015-06-22 17:42:30

标签: swift dictionary nested

我正在尝试更新未知类型的复杂Dictionary中的值,因为它包含String和子词典。我的初始化功能代码如下。

这是我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"]
    ]
]

这是我的代码:

我从defaultParamsDictionary)获取额外值并插入methodsDictionary)。

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中插入缺失的值。

2 个答案:

答案 0 :(得分:2)

这有点令人费解,但它确实有效:

library(rvest)
library(data.table)


test<-read_html("test.html") 
    data.table(do.call(cbind,lapply(c("fileid","code","value","ivalue","icode","itype"),function(i){
        test %>%
        html_nodes(i)%>%
        html_text()


    })))

         V1  V2     V3   V4  V5 V6
    1: 12347 ABC 100000 1000 CDF  R
    2: 12347 ABC 100000 1500 EGK  R
    3: 12347 ABC 100000  300 TSR  R

结果:

  

[卡拉奇:[params:{       FJ = 15;       IS = 15;       午夜=标准;       偏移=&#34; 0分钟&#34 ;;   },名字:卡拉奇时间],旁遮普:[params:{       FJ = 18;       IS = 17;       午夜=标准;       偏移=&#34; 0分钟&#34 ;;   },名字:旁遮普时间],拉合尔:[params:{       FJ =&#34; 19.5&#34 ;;       IS =&#34; 17.5&#34 ;;       MG =&#34; 8.9&#34 ;;       午夜=标准;       偏移=&#34; 0分钟&#34 ;;   },姓名:拉合尔城时间]]

答案 1 :(得分:0)

而不是== nil,您应该使用if let关闭,我不知道您要分配哪个值,但这种方法可行。

if let value = params.objectForKey(defaultParamKey) as? String {
           params[defaultParamKey] = value
}