Created
June 15, 2020 17:56
-
-
Save kongzii/6f6353a4e45c456ba6d15b7931712192 to your computer and use it in GitHub Desktop.
Python defaultdict in Swift
This file contains hidden or 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
public extension Dictionary { | |
/// - Parameter key: Key to retrieve from self. | |
/// - Parameter or: Value that will be set for `key` if `self[key]` is nil. | |
subscript(key: Key, or def: Value) -> Value { | |
mutating get { | |
self[key] ?? { | |
self[key] = def | |
return def | |
}() | |
} | |
set { self[key] = newValue } | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment