user1904954
user1904954

Reputation: 63

Sort indexPathsForSelectedRows in Swift

When you invoke tableView.indexPathsForSelectedRows(), it returns an array of AnyObject type with the indexPaths of the rows selected in the order that user has selected them.

What I want is to sort the indexPaths in order to get ascending order. Before Swift, it could be achieved with this:

NSArray *sortedIndexPaths = [[tableView indexPathsforSelectedRows]
sortedArrayUsingSelector:@selector(compare:)];

But I have tried to implement it with Swift and it does not work :S

Anyone knows how to deal with this?

Thanks in advance!

Upvotes: 3

Views: 3394

Answers (4)

Digvijay Gida
Digvijay Gida

Reputation: 89

Here is Sort indexPathsForSelectedRows swift 4 code.

    if var selection = tableView.indexPathsForSelectedRows
    {
       selection = selection.sorted{ $1.compare($0) == .orderedAscending }

    }

If you have any issue ping me.

Upvotes: 0

Allen Zeng
Allen Zeng

Reputation: 2665

You can overload the < and > operators and then just call sort on it.

Define this globally

func <(left: NSIndexPath, right: NSIndexPath) -> Bool {
    return left.section < right.section || left.row < right.row
}

Then you can just do this for ascending

let sortedIndexPaths = tableView.indexPathsForSelectedRows?.sort(<)

Obviously because of it returns an optional you would guard against it somehow, for example

guard let sortedIndexPaths = tableView.indexPathsForSelectedRows?.sort(<) else {
    return
}

Upvotes: 2

Eugene Braginets
Eugene Braginets

Reputation: 856

it's simple code to sort array of NSIndexPath objects stored in paths variable . The trick is in casting to [NSIndexPath]. Now you can have your array sorted.

let paths = tableView.indexPathsForSelectedRows() as [NSIndexPath]
let sortedArray = paths.sorted {$0.row < $1.row}

OR if you wish to have separate function for that like:

func compare (obj0: NSIndexPath, obj1: NSIndexPath) -> Bool {
 return obj0.row < obj1.row
}

then

let sortedArray = paths.sorted { compare($0, $1) }

Upvotes: 3

I'm on Windows 7 at the moment so I cannot test but this is what I would expect to work. It may need a type annotation.

let paths = tableView.indexPathsforSelectedRows()
let sorted = paths.sortedArrayUsingSelector("compare:")

Upvotes: 2

Related Questions