Skip to content

Instantly share code, notes, and snippets.

@kiliankoe
Last active July 4, 2016 09:58
Show Gist options
  • Select an option

  • Save kiliankoe/cd91d97748578ae43ff50a5979e45ae1 to your computer and use it in GitHub Desktop.

Select an option

Save kiliankoe/cd91d97748578ae43ff50a5979e45ae1 to your computer and use it in GitHub Desktop.
Dictionary Map
extension Dictionary {
func mapD<T: Hashable, U>(_ elementClosure: ((key: T, value: U) -> (T, U))) -> Dictionary<T, U> {
return self.map { (tuple) in
return elementClosure(key: tuple.0 as! T, value: tuple.1 as! U) // The compiler demands these casts exist 😕
}.toDictionary()
}
}
extension Sequence {
func toDictionary<T: Hashable, U>() -> Dictionary<T, U> {
var returnDict = [T : U]()
for i in self {
let tuple = i as! (T, U)
returnDict[tuple.0] = tuple.1
}
return returnDict
}
}
let dict = [
1: ["foo", "bar"],
2: ["bar", "baz"]
]
let newDict = dict.mapD { (key, value) in
(key, value.sorted())
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment