如何在swift中安全地展开nil值?

时间:2015-06-20 16:47:02

标签: swift dictionary

我对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词典中的键currencynamerawrate字典中的任何键都不匹配。

据我所知,在使用let if组合密钥之前,我必须以某种方式检查密钥是否存在于两个字典中?但我对语法感到困惑......我也试图使用可选值而没有成功。

所以我的问题是如何将这两个字典组合在一起,并省略了EUR combinedDictionary,因为rawrate字典中没有匹配的键?

感谢您的帮助!

1 个答案:

答案 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)
    }
}