Created
October 1, 2018 11:08
-
-
Save ts95/4f5d3a25514558bf36da949e791cc309 to your computer and use it in GitHub Desktop.
Array extension method for generating a look-up table
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 Array { | |
/// Returns a dictionary keyed by an arbitrary attribute of an element in the array. | |
/// | |
/// The returned dictionary can be used for look-ups by an arbitrary attribute | |
/// in an array of models with constant time complexity instead of the typical | |
/// linear complexity associated with looking up elements in an unsorted list. | |
/// | |
/// - Parameters: | |
/// - indexClosure: Callback used to specify which attribute should be used for look-ups (usually an ID) | |
func lookupTable<Index: Hashable>(indexedBy indexClosure: (Element) -> Index) -> [Index : Element] { | |
return .init(uniqueKeysWithValues: map { (indexClosure($0), $0) }) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment