问题
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