A possible solution:
let sorted = objects.flatMap { obj in
ids.index(of: obj.id).map { idx in (obj, idx) }
}.sorted(by: { $0.1 < $1.1 } ).map { $0.0 }
Explanation:
- First, each object is tied to together with the corresponding
position of the id in the array, this gives an array of
(object, index) tuples.
- This array is sorted with respect to the index positions.
- Finally, the objects are extracted again.
Possible advantages:
- Each object is searched only once in the array.
- Objects for which no id exists in the array are ignored.