Created
June 27, 2017 23:11
-
-
Save humblehacker/30713566c7a1884e339384bc83a46a12 to your computer and use it in GitHub Desktop.
Swift 3 implementation of Kotlin's associateBy for transforming a Sequence to a Dictionary
This file contains 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
public | |
extension Sequence | |
{ | |
/// Returns a Dictionary using the result of `keySelector` as the key, and the result of `valueTransform` as the value | |
public func associateBy<T, K: Hashable, V>(_ keySelector: (T) -> K, _ valueTransform: (T) -> V) -> [K:V] where T == Iterator.Element | |
{ | |
var dict: [K:V] = [:] | |
for element in self { | |
dict[keySelector(element)] = valueTransform(element) | |
} | |
return dict | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment