iosswiftsetnscountedset

Is there more efficient way to keep custom object array unique by each pagination data feeds?


In the tableView's willDisplay checks latest cell and then trigger new request for upcoming datas cited as pagination.

I want to keep that custom object array's IDs as unique with upcoming datas too.

I tried below solution to make it, but I wonder that Is there anything to do more efficiently?

let idSet = NSCountedSet(array: (newDatas + self.ourDatas).map { $0.id })
let arr = (newDatas + self.ourDatas).filter { idSet.count(for: $0.id) == 1 }
self.ourDatas = arr // ourDatas is dataSource of tableView
self.tableView.reloadData()

Also above way mixes all datas, how can I continue keeping it as ordered?


Solution

  • You should keep two properties; your array of items (ourDatas) and a set of ids (var ourIds = Set<String>(). I am assuming your ids are Strings

    You can do something like this

    var insertedRows = [IndexPath]()
    for newItem in newDatas {
       if !ourIds.contains(newItem.id) {
          insertedRows.append(IndexPath(item:self.ourDatas.count,section:0))
          ourIds.insert(newItem.id)
          ourDatas.append(newItem)
       }
    }
    
    if !insertedRows.empty {
       self.tableView.insertRows(at: insertedRows, with:.automatic)
    }