view raw
Drix Drix - 9 months ago 46
iOS Question

Order two arrays using Swift

The problem is the follow:

I have two arrays, one with objects, the second with CoreData entities sorted by ids:

var objects = [["id":5],["id":1],["id":3]]
var entities = [["id":1],["id":3],["id":5]]

I need to sort the entities in the same order as the objects.
* the entities aim saved yet

I can do it through a loop in a loop, and creating a third array but it is slow and use more memory than it should (My arrays will handle more than 100 entities sometimes)

let count = objects.count
var finalArray = []()
for i in 0..<count {
let id = objects[i].id
for k in 0..<count {
if entities[k].id == id {
finalArray += [entities[k]]

The code above does work, but it doesn't smells good enough. Any suggestion how to use a build-in Swift more optimal solution?


This isn't really a Swift question. It's an algorithm question. You'd do it the same way in any language.

First, build a map from id to entity. Then, use the map to look up the entities efficiently.

var entityForId = [Int:MyEntity]()
for entity in entities {
    entityForId[] = entity

var finalArray = [MyEntity]()
for object in objects {
    if let entity = entityForId[] {

You can replace the second loop with a single line:

var finalArray = objects.flatMap({ entityForId[$] })

I find the use of flatMap makes the code clearer here, but if you're not familiar with it, you might prefer the explicit loop.