Skip to content

Instantly share code, notes, and snippets.

@JohnSundell
Created June 5, 2017 10:21
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JohnSundell/8cd675792c252cc20ff0de2c1433bf53 to your computer and use it in GitHub Desktop.
Save JohnSundell/8cd675792c252cc20ff0de2c1433bf53 to your computer and use it in GitHub Desktop.
A map method for Dictionary that lets you easily transform its keys and values into other types
extension Dictionary {
func map<K: Hashable, V>(_ transform: (Element) throws -> (key: K, value: V)) rethrows -> [K : V] {
var transformed = [K : V]()
for pair in self {
let transformedPair = try transform(pair)
transformed[transformedPair.key] = transformedPair.value
}
return transformed
}
}
let dictionary = [
"hello": 1,
"world": 2
]
let transformed = dictionary.map { pair in
return (pair.key, Double(pair.value))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment