xxtesaxx xxtesaxx - 1 year ago 75
Swift Question

Equivalent of Androids DiffUtil for Swift / iOS or other effective implementation

In my app I have to load some data from a web service. Then I have to sort the data by properties of models of a collection property of the model and then update my collectio view with the new data.

Unfortunately I have no clue how I can know which cell moved to which new position. On Android, I used DiffUtil in the past but I'm not aware of a Swift equivalent to animate the changes in my collection view.

Heres the data model I use. For the this example, I omit all the other fields and use protocols to make it clearer (at least I hope this makes it clearer):

protocol Alert {
var date: Date
var statusType: StatusType
}

protocol Status {
var statusType: StatusType
var level: Level
}

protocol Device {
var states: [Status] //Contains never more than 1 Status of each StatusType so its basically a set
var alertsByStatusType: [StatusType: [Alert]]
}

enum StatusType {
case someStatus, someOtherStatus
}

enum Level {
case low, medium, high
}


The web service returns me a device which contains a collection of Status and a collection of Alert.

//Web service model kind of sucks
protocl WebServiceDevice {
var states: [Status]
var alerts: [Alert]
}


In the device constructor, I do some manually sorting and mapping to build the
alertsByStatusType
dictionary. I also sort the
Status
collection by the
Status.level
so that first, all "high" level states come, then the "medium" level and finally the "low" level states.

Inside the same level, I then have to sort by the
Alerts.date
so when two
Status
have the same
Level
, the one with the more recent
Alert
comes first.

I know, this data model I get from the web service is terrible to begin with and I begged for a proper model where the alerts are inside their corresponding states and the states are properly sorted but hey, thats life.

Now when I display all states in a tableview, let's say a
Status
with
level == low
gets and alert, then the level will change and after updating my data from the web service and sorting everything, it will be further to the beginning in the
Device.states
collection. How can I know from which indexPath I have to move the cell to which new indexPath?

I hope you understand what I mean and what the problem is. Basically I have to find out which
Status
has a different
Level
and from where to where it has moved in the data source of my table view so I can animate the changes instead just call
reload()
on the table view.

Answer Source

There is no builtin functionality for this, but there are a few good 3rd party Swift solutions. I recommend ChangeSet, and have heard others recommend Dwifft.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download