Swift标准词典是否具有获取或设置功能? [英] Does the Swift standard Dictionary have a get-or-set function?
本文介绍了Swift标准词典是否具有获取或设置功能?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我发现自己开始想要这样的东西:
I found myself starting to want something like this:
extension Dictionary {
mutating func get(_ key: Key, backup: Value) -> Value {
if let stored = self[key] {
return stored
} else {
self[key] = backup
return backup
}
}
}
但是根据我的经验,Swift忽略了类似的事情,因为它有一种替代的(预期的)方法.我还没有在文档中找到这种方法. 我是否错过了此功能,还是应该创建它?此外,如果他们遗漏了该功能并且我不应该创建它,为什么?
but in my experience, Swift leaves out things like this because it has an alternative (intended) way to do it. I haven't found such a way in documentation. Did I miss this function, or should I create it? Also, if they left it out and I shouldn't create it, why?
推荐答案
否,它没有这样的功能.在这种情况下,最好创建一个扩展.
No it doesn't have a function like this. It is fine to create an extension in this circumstance.
这篇关于Swift标准词典是否具有获取或设置功能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文