Last active
July 4, 2016 09:58
-
-
Save kiliankoe/cd91d97748578ae43ff50a5979e45ae1 to your computer and use it in GitHub Desktop.
Dictionary Map
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 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