Skip to content

Instantly share code, notes, and snippets.

@IanKeen
Created July 7, 2018 20:09
Show Gist options
  • Save IanKeen/52aaa4d29d7084eea7f42c6e656ab1b8 to your computer and use it in GitHub Desktop.
Save IanKeen/52aaa4d29d7084eea7f42c6e656ab1b8 to your computer and use it in GitHub Desktop.
Map from `Dictionary<Key, Value>` to `Dictionary<T, U>`
public extension Dictionary {
public func mapPairs<T: Hashable, U>(_ transform: ((key: Key, value: Value)) throws -> (key: T, value: U)) rethrows -> [T: U] {
return .init(uniqueKeysWithValues: try self.map(transform))
}
}
let x = ["1": 1, "2": 2, "3": 3]
let y = x.mapPairs { (Int($0.key)!, "\($0.value)") }
print(x) // ["1": 1, "2": 2, "3": 3]
print(y) // [1: "1", 2: "2", 3: "3"]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment