Skip to content

Instantly share code, notes, and snippets.

@ts95
Created October 1, 2018 11:08
Show Gist options
  • Save ts95/4f5d3a25514558bf36da949e791cc309 to your computer and use it in GitHub Desktop.
Save ts95/4f5d3a25514558bf36da949e791cc309 to your computer and use it in GitHub Desktop.
Array extension method for generating a look-up table
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