Last active
August 22, 2017 14:04
-
-
Save alobanov/0e597aed9ff215fe7a05493767fc162b to your computer and use it in GitHub Desktop.
Array sorting by predefined sorting ids list
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
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