Skip to content

Instantly share code, notes, and snippets.

@jordanekay
Last active February 11, 2021 16:01
Show Gist options
  • Star 14 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save jordanekay/3e4f46d9f9e0d50c2b7b to your computer and use it in GitHub Desktop.
Save jordanekay/3e4f46d9f9e0d50c2b7b to your computer and use it in GitHub Desktop.
Mapping dictionaries in Swift
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