我对swift很新,我正在努力了解如何处理nil vars ......
我有两个词典:
var currencyname: NSDictionary = [
"CNY": "Chinese Yuan",
"PLN": "Polish Zloty"
"EUR": "Euro"
]
var rawrates NSDictionary = [
"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]!)
}
但是我收到found nil while unwrapping an Optional value
错误,因为EUR
词典中的键currencyname
与rawrate
字典中的任何键都不匹配。
据我所知,在使用let if
组合密钥之前,我必须以某种方式检查密钥是否存在于两个字典中?但我对语法感到困惑......我也试图使用可选值而没有成功。
所以我的问题是如何将这两个字典组合在一起,并省略了EUR
combinedDictionary,因为rawrate
字典中没有匹配的键?
感谢您的帮助!
答案 0 :(得分:1)
我认为你所追求的是这样的:
let currencyname = [
"CNY": "Chinese Yuan",
"PLN": "Polish Zloty",
"EUR": "Euro"
]
let rawrates = [
"CNY": "1.34",
"PLN": "1.456"
]
var combinedDictionary = [String:(name:String,rate:String)]()
for key in currencyname.keys {
if let val1 = currencyname[key], val2 = rawrates[key] {
combinedDictionary[key] = (val1,val2)
}
}
但如果没有更明确的问题陈述,那就有点难以确定。在任何情况下,这都不是我建议的。在我看来,这是一个更好的结果:
let currencyname = [
"CNY": "Chinese Yuan",
"PLN": "Polish Zloty",
"EUR": "Euro"
]
let rawrates = [
"CNY": "1.34",
"PLN": "1.456"
]
struct Currency {
let name : String
let rate : String
}
var combinedDictionary = [String:Currency]()
for key in currencyname.keys {
if let val1 = currencyname[key], val2 = rawrates[key] {
combinedDictionary[key] = Currency(name:val1, rate:val2)
}
}