Last active
January 31, 2018 11:07
-
-
Save kakajika/6f07b6ae004e385a3b46ab54245ce998 to your computer and use it in GitHub Desktop.
A port of Kotlin-stdlib's associate method to Swift 4.
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 Sequence { | |
func associate<K, V>(_ transform: (Element) -> (K, V)) -> [K: V] { | |
return self.reduce(into: [:]) { (dict, element) in | |
let (key, value) = transform(element) | |
dict[key] = value | |
} | |
} | |
func associateBy<K>(_ keySelector: (Element) -> K) -> [K: Element] { | |
return self.reduce(into: [:]) { (dict, element) in | |
dict[keySelector(element)] = element | |
} | |
} | |
func associateBy<K, V>(_ keySelector: (Element) -> K, _ valueTransform: (Element) -> V) -> [K: V] { | |
return self.reduce(into: [:]) { (dict, element) in | |
dict[keySelector(element)] = valueTransform(element) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment