当前位置 : 主页 > 手机开发 > 其它 >

如何在Swift中结合两个NSDictionary

来源:互联网 收集:自由互联 发布时间:2021-06-11
我是一个快速的初学者,我试图理解字典的概念. 我有两个NSDictionary,它们都包含相同的键,如下所示: var currencyname: NSDictionary = [ "CNY": "Chinese Yuan", "PLN": "Polish Zloty"]var rawrates NSDictionary =
我是一个快速的初学者,我试图理解字典的概念.

我有两个NSDictionary,它们都包含相同的键,如下所示:

var currencyname: NSDictionary = [
        "CNY": "Chinese Yuan",
        "PLN": "Polish Zloty"
]

var rawrates NSDictionary = [
        "CNY": "1.34",
        "PLN": "1.456"
]

我试图将它们组合起来,这样我只得到一个字典,例如:

["CNY": "Chinese Yuan","1.34"]
        ["PLN": "Polish Zloty","1.456"]

我想我的第一个问题是我应该输出什么类型的变量?我可以使用NSDictionary吗?通过阅读文档,我的理解是NSDictionaries通过成对的键/值来工作.是否可以在字典中放入两个值?

我的第二个问题是我应该如何组合这两个字典,我试图使用下面的代码而没有太大的成功

for (currency, rawrate) in rawrates {
                for (currencyid, name) in currencyname{
                    if currency == currencyid {
                        rawrates.append(name as String)
                    }
                } 
}
您可以创建元组字典,如下所示:

let currencyname:[String:String] = ["CNY": "Chinese Yuan", "PLN": "Polish Zloty"]
let rawrates:[String:String] = ["CNY": "1.34", "PLN": "1.456"]

var combinedDictionary:[String:(name:String,rate:String)] = [:]


for key in currencyname.keys.array {
    combinedDictionary[key] = (currencyname[key]!,rawrates[key]!)
}


// Testing

combinedDictionary["PLN"]!       // (.0 "Polish Zloty", .1 "1.456")
combinedDictionary["PLN"]!.name  // "Polish Zloty"
combinedDictionary["PLN"]!.rate  // "1.456"

combinedDictionary["CNY"]!       // (.0 "Chinese Yuan", .1 "1.34")
combinedDictionary["CNY"]!.name  // "Chinese Yuan"
combinedDictionary["CNY"]!.rate  // "1.34"
网友评论