Last active
February 11, 2021 16:01
-
-
Save jordanekay/3e4f46d9f9e0d50c2b7b to your computer and use it in GitHub Desktop.
Mapping dictionaries in Swift
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 { | |
public func map<T: Hashable, U>(@noescape transform: (Key, Value) -> (T, U)) -> [T: U] { | |
var result: [T: U] = [:] | |
for (key, value) in self { | |
let (transformedKey, transformedValue) = transform(key, value) | |
result[transformedKey] = transformedValue | |
} | |
return result | |
} | |
public func map<T: Hashable, U>(@noescape transform: (Key, Value) throws -> (T, U)) rethrows -> [T: U] { | |
var result: [T: U] = [:] | |
for (key, value) in self { | |
let (transformedKey, transformedValue) = try transform(key, value) | |
result[transformedKey] = transformedValue | |
} | |
return result | |
} | |
} | |
let dict = ["A": "a", "B": "b"] | |
dict.map { (key, value) in | |
(key.lowercaseString, value.uppercaseString) | |
} | |
// Result is ["a": "A", "b": "B"] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment