Skip to content

Instantly share code, notes, and snippets.

@humblehacker
Created June 27, 2017 23:11
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save humblehacker/30713566c7a1884e339384bc83a46a12 to your computer and use it in GitHub Desktop.
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
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