I have an array of sections:
struct Section {
let title: String
var items: [Item]
}
Which contains a list of items:
struct Item {
let title: String
}
I'd like to populate this with an unknown amount of items, and sort the data as efficiently as possible. I fetch the data from a remote source, and parse the data as it comes in. I can't know if the data being sent is sorted or not, so blindly appending to a Section list may not work here.
I'd like the data to be shown to the user as soon as it comes in (in batches), so I can't wait until the end of the fetch operation to perform sorting. For examples sake, lets assume I'm getting the section by:
let item = Item(title: "Foo")
let sectionTitle = item.characters.first!
if let section = sections.filter({ $0.title == String(sectionTitle) }) {
// find
} else {
// create
}
My initial idea, once I've figured out the correct Section, loop through the Section items until sectionItem.title > item.title, then that becomes the insertion point:
var insertionPoint = 0
for (i, val) in array.enumerated() {
insertionPoint = i
if val.title > item.title { break }
}
section.items.insert(item, at: insertionPoint)
This does seem inefficient once the Section has many Item objects. Is there a more appropriate method?
My only other thought would be to keep track of Section items that were touched in this batch, then running section.items.sort() at the end of each batch operation.