Finding the difference between two Arrays

Published by donnywals on

Many applications work with data, often they are built to retrieve data and display this data to the user in a table view, collection view, list (if you’re using SwiftUI) or a different kind of component. It’s not uncommon for this data to change and when it does you might be interested in figuring out what elements were added to the data and which items were removed. This isn’t always straightforward so up until now you might have written code something like the following:

Simple and effective, much easier than figuring out the difference and only reloading the cells that have changed. On iOS 13, you can use new methods on any collection that conforms to BiDirectionalCollection to determine the changes between two collections as long as the items that are contained in the collection conform to Equatable. You can then use the information from this method to update a table view:

Tip:
If your elements are not Equatable, use the differences(from:by:) method to supply a closure where you can perform your own comparison to determine if two elements are equal.

Cool stuff right? What kind of applications do you see for this kind of method? Let me know on Twitter!

Categories: Quick Tip