Swift-带数组的字典-获取对数组的引用 [英] Swift - dictionary with array - get reference to array
本文介绍了Swift-带数组的字典-获取对数组的引用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我目前有以下代码:
var dic = [String: [String]]()
if (dic.index(forKey: key) != nil){
dic[key]?.append(m)
}
else {
dic[key] = [m]
}
但是,在dic.index(forKey: key)
和dic[key]?.append(m)
中,我两次计算了密钥.
However, in dic.index(forKey: key)
and dic[key]?.append(m)
I calculate the key twice.
是否可以做这样的事情?:
Is there a possibility to do something like this?:
var dictKeyVal = &dic[key]
if (dictKeyVal != nil) {
dictKeyVal?.append(m)
}
else {
dic[key] = [m]
}
如果没有键,我在key或nil处获得对数组的引用
where I get the reference to array at key or nil if there is no key
推荐答案
您只需为下标使用默认值,您的整个代码就会简化为:
You can simply use a default value for the subscript and your whole code will be simplified to this:
var dic = [String: [String]]()
dic[key, default: []].append(m)
这篇关于Swift-带数组的字典-获取对数组的引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文