Created
June 5, 2017 10:21
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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