Skip to content

Instantly share code, notes, and snippets.

@bennokress
Created May 29, 2017 11:22
Show Gist options
  • Save bennokress/53de8ab693b3d25e601be40e7e98b272 to your computer and use it in GitHub Desktop.
Save bennokress/53de8ab693b3d25e601be40e7e98b272 to your computer and use it in GitHub Desktop.
Extensions for Swift's Dictionaries
extension Dictionary where Value == Any {
// Usage: dict.value(forKey: "age", defaultValue: 100) … works with every type!
func value(forKey key: Key, defaultValue: @autoclosure () -> T) -> T {
guard let value = self[key] as? T else {
return defaultValue()
}
return value
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment