Banana Banana - 3 months ago 19
Swift Question

Reorder array compared to another array in Swift

I have one array in Swift containing some ids of objects, and I have another array containing these objects with their ids, so something like this:

class MyObject {
let id: String
...
}

let ids: [String] = ...
let objects: [MyObject] = ...


Now the array of ids is sorted in some custom order, and I need the array of objects to be sorted in the same order. So for example:

let ids: [String] = ["1", "2", "3"]
let objects: [MyObject] = [obj3, obj1, obj2]
// obj1.id = "1"
// obj2.id = "2"
// obj3.id = "3"
objects.reorder(template: ids)
// Now objects = [obj1, obj2, obj3]


So I basically need to implement this reorder method.
Does anyone have a smart suggestion how to do this in Swift? I'm using Swift 3, so all the new APIs are available to me.

Answer

You can sort objects in order to follow the order in ids writing

let sorted = objects.sort { ids.indexOf($0.id) < ids.indexOf($1.id) }
// [{id "1"}, {id "2"}, {id "3"}]

Another example

let ids: [String] = ["3", "2", "1"]
let objects: [MyObject] = [MyObject(id: "3"), MyObject(id: "1"), MyObject(id: "2")]

let sorted = objects.sort { ids.indexOf($0.id) < ids.indexOf($1.id) }
// [{id "3"}, {id "2"}, {id "1"}]

This code is in Swift 2.2

Comments