Skip to content

Instantly share code, notes, and snippets.

@jverkoey
Last active November 5, 2015 09:11
Show Gist options
  • Save jverkoey/0b993932ddc9bd69120d to your computer and use it in GitHub Desktop.
Save jverkoey/0b993932ddc9bd69120d to your computer and use it in GitHub Desktop.
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