Skip to content

Instantly share code, notes, and snippets.

@alobanov
Last active August 22, 2017 14:04
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alobanov/0e597aed9ff215fe7a05493767fc162b to your computer and use it in GitHub Desktop.
Save alobanov/0e597aed9ff215fe7a05493767fc162b to your computer and use it in GitHub Desktop.
Array sorting by predefined sorting ids list
extension Array {
func sortByArray<T, Z: Hashable>(of ids:[Z],
keyType: Z.Type,
idClosure: (_ obj: T) -> (Z)) -> [T] {
var dict = [Z: T]()
guard let arr = self as? [T] else {
return []
}
for o: T in arr {
let key = idClosure(o)
dict[key] = o
}
var output = [T]()
for itemID in ids {
if let obj = dict[itemID] {
output.append(obj)
}
}
return output
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment