Determine if an array has changed after sorting
I would like to determine if the TableView should be reloaded. When it comes up, I do a simple name based look.
I could revert to this view with more or less items in the data source, or a modified item in the data source that requires cell ordering. those. name changed from Foo to Bar hence order change.
How can I determine if a list has mutated after using Swift's sort method? I am looking for something like this
let orderDidChange = clientList.sort({ $0.clientName < $1.clientName })
Here is my current code
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
let originalList = clientList
orderHasChanged = false
clientList.sort({ $0.clientName < $1.clientName })
clientList.sort({ $0.isBase > $1.isBase })
orderHasChanged = clientList != originalList
if orderHasChanged {
// always enters here
println("changed")
tableView.beginUpdates()
tableView.reloadSections(NSIndexSet(index: 0), withRowAnimation: UITableViewRowAnimation.Fade)
tableView.endUpdates()
}
else {
println("same do nothing")
}
}
In fact, you can just check if the old array is equal to the sorted array using the operator ==
. If two arrays contain the same data but in a different order, they are not equal.
For example,
let bar: [String] = ["Hello", "World"]
let foo: [String] = ["Hello", "World"]
//this will print "true"
//bar and foo contain the same data in the same order
print(bar == foo)
let bar: [String] = ["Hello", "World"]
let foo: [String] = ["World", "Hello"]
//this will print "false"
//bar and foo contain the same data, but in a different order
print(bar == foo)
So something like this will work
let originalList = clientList
clientList.sort({ $0.clientName < $1.clientName })
let orderHasChanged = clientList != originalList
This is the shortest I could think of. First you need to add the flag as a property and then change the modified view below where the flag is set based on whether or not the sorted has occurred. If it hasBeenSorted then reload the tableView or not.
//private property
var hasBeenSorted = false
//var names = [3, 1, 4, 2]
var names = [1, 2, 3, 4]
names.sort({
let isLess = $0 < $1
//binary OR since we are interested only when it is true
hasBeenSorted = isLess || hasBeenSorted
return isLess
})
hasBeenSorted //false