JakeTheDog
JakeTheDog

Reputation: 21

Different ways of setting an index of an array used by a UITableView

Question,

Does anyone have a tidier solution compared to what I have done below?

Setup,

I need to download load data from a backend and put it into a tableView in a specific order that is determined from the backend.

Problem,

I get the list order from the backend but the order is messed up cause I was appending to an array. When I tried to add to a specific index I would get index out of range (of course) cause if the first item downloaded was supposed at index 6 then it would be out of range.

My solution,

Here is my solution that works but I am interested in seeing how someone could improve on this or sees another way to accomplish the same thing,

 if self.array.count >= indexNumberFromBackend {
        self.array.insert(data, at: indexNumberFromBackend)
    } else {
        if indexNumber > self.array.count {
            if self.array.count <= indexNumberFromBackend {
               self.array.append(data)
            } else {
               self.array.insert(data, at: indexNumberFromBackend)
            }
        }
    }

Upvotes: 0

Views: 33

Answers (3)

JakeTheDog
JakeTheDog

Reputation: 21

With the help of Andy and Conrad my code became this,

self.myArray.append(data)
self.myArray.sort(by: { $0.cellOrder > $1.cellOrder })

Upvotes: 1

Andy Taylor
Andy Taylor

Reputation: 102

Couldn't you just sort the array?

Upvotes: 1

konrad.bajtyngier
konrad.bajtyngier

Reputation: 1786

You could consider putting data in a dictionary and then generate a sorted array. Alternatively, you could store the backend index along with the data to sort the array later.

Upvotes: 1

Related Questions