Last active
November 5, 2015 09:11
-
-
Save jverkoey/0b993932ddc9bd69120d to your computer and use it in GitHub Desktop.
Swift Dictionary get-with-default extension
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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