Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Swift Dictionary get-with-default extension
import Foundation
extension Dictionary {
/**
Returns the value for the given key if it exists, otherwise stores and returns the result of
withDefault.
Example usage:
var dictionary: [String:[String]] = [:]
dictionary["foo", withDefault: []].append("bar")
*/
subscript(key: Key, @autoclosure withDefault value: Void -> Value) -> Value {
mutating get {
if self[key] == nil {
self[key] = value()
}
return self[key]!
}
set {
self[key] = newValue
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.