Skip to content

Instantly share code, notes, and snippets.

@kongzii
Created June 15, 2020 17:56
Show Gist options
  • Save kongzii/6f6353a4e45c456ba6d15b7931712192 to your computer and use it in GitHub Desktop.
Save kongzii/6f6353a4e45c456ba6d15b7931712192 to your computer and use it in GitHub Desktop.
Python defaultdict in Swift
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