Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determine if an array changed after sorting

Tags:

arrays

ios

swift

I would like to determine if I should reload a TableView. When it appears, I do a simple sort based on names.

I could segue back to this view with more or less items in the dataSource, or a altered item in the data source that requires a re ordering of the cells. i.e., name changed from Foo to Bar, hence order change.

How do I determine if mutation of the list occurred after using the Swift sort method? I'm 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")
    }

}
like image 690
DogCoffee Avatar asked Sep 17 '26 16:09

DogCoffee


1 Answers

You can actually just check if the old array equals the sorted array by 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 would work

let originalList = clientList
clientList.sort({ $0.clientName < $1.clientName })

let orderHasChanged = clientList != originalList
like image 169
Jojodmo Avatar answered Sep 19 '26 11:09

Jojodmo