Last active
December 14, 2016 20:54
-
-
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
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
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