Does the Swift standard Dictionary have a get-or-set function?

淺唱寂寞╮ 提交于 2019-12-12 13:11:51

问题


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
        }
    }
}

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?


回答1:


No it doesn't have a function like this. It is fine to create an extension in this circumstance.




回答2:


There isn't a specific function like this in Swift.

As I'm sure you know, you can search a Dictionary in Swift:

var stringsAsInts: [String:Int] = [
"zero" : 0,
"one" : 1,
"two" : 2,
"three" : 3,
"four" : 4,
"five" : 5,
"six" : 6,
"seven" : 7,
"eight" : 8,
"nine" : 9
]

stringsAsInts["zero"] // Optional(0)
stringsAsInts["three"] // Optional(3)
stringsAsInts["ten"] // nil

// Unwaraping the optional using optional binding
if let twoAsInt = stringsAsInts["two"] {
print(twoAsInt) // 2
}

// Unwaraping the optional using the forced value operator (!)
stringsAsInts["one"]! // 1

... and then set a value

However generating an extension or function is your best option in this case.

Hope this helps clear things up :)



来源:https://stackoverflow.com/questions/41001705/does-the-swift-standard-dictionary-have-a-get-or-set-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!