Skip to content

Instantly share code, notes, and snippets.

@jarsen
Created May 31, 2015 14:49
Show Gist options
  • Save jarsen/1a4cfdf547a201243b15 to your computer and use it in GitHub Desktop.
Save jarsen/1a4cfdf547a201243b15 to your computer and use it in GitHub Desktop.
Dictionary Update
extension Dictionary {
mutating func update(key: Key, initial: Value, update:Value->Value) {
if let x = self[key] {
self[key] = update(x)
}
else {
self[key] = initial
}
}
}
var foo = ["a":1, "b":2, "c":3]
foo.update("b", initial: 1) { x in x + 1 }
foo.update("d", initial: 1) { x in x + 1 }
foo
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment