Skip to content

Instantly share code, notes, and snippets.

Last active November 5, 2015 09:11
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
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
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