Skip to content

Instantly share code, notes, and snippets.

@olgakogan
Created October 31, 2014 13:49
Show Gist options
  • Save olgakogan/bd6e5eff98aeda63c68c to your computer and use it in GitHub Desktop.
Save olgakogan/bd6e5eff98aeda63c68c to your computer and use it in GitHub Desktop.
Swift - get from dictionary, with default value
extension Dictionary {
func get(key: Key, defaultValue: Value) -> Value {
/**
Returns the value for the given key (if exists), otherwise returns the default value.
*/
if let value = self[key] {
return value
} else {
return defaultValue
}
}
}
@multics
Copy link

multics commented Aug 16, 2018

It seems dict[key, default: value] is what you need.

Here is the API reference.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment