Skip to content

Instantly share code, notes, and snippets.

@mluisbrown
Last active December 14, 2016 20:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mluisbrown/92d2fc1b7e18ddb51ea1305490ccc780 to your computer and use it in GitHub Desktop.
Save mluisbrown/92d2fc1b7e18ddb51ea1305490ccc780 to your computer and use it in GitHub Desktop.
Generic Swift function to convert an Array into a Dictionary using a key from each object in the Array
func dict<T, U: Hashable>(from array: [T], getKey: (T) -> U) -> [U : T] {
var dict: [U : T] = .init(minimumCapacity: array.count)
array.forEach {
dict[getKey($0)] = $0
}
return dict
}
// Collection extension as suggested by https://github.com/dmcrodrigues
extension Collection {
func dictionary<U: Hashable>(withKey keyGenerator: (Iterator.Element) -> U) -> [U : Iterator.Element] {
var result: [U : Iterator.Element] = .init(minimumCapacity: underestimatedCount)
forEach { result[keyGenerator($0)] = $0 }
return result
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment