Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift: Sort Array by sort descriptors

I am using coredata so I need sort descriptors for my entities

For example, a Coordinate-entity has this class func:

class func sortDescriptors() -> Array<NSSortDescriptor>
{
    return [NSSortDescriptor(key: "sequence", ascending: true)]
}

I am using this when doing fetch-requests to CoreData like this:

var request = NSFetchRequest(entityName: entityName)

request.sortDescriptors = T.sortDescriptors()

However, when I have an array of coordinates as a property on another coredata object, this is an NSSet (I.e. unsorted)

To solve this, I am returning the coordinates like this:

return NSArray(array: coordinates!).sortedArrayUsingDescriptors(Coordinate.sortDescriptors()) as? Array<Coordinate>

Which feels ugly, to use an NSArray just to get the sortedArrayUsingDescriptors-method. Is there a similar way to do this directly on a Swift-array, I.e. Array<Coordinate> by using sort descriptors?

Thank you!

like image 327
ullstrm Avatar asked Nov 12 '14 09:11

ullstrm


1 Answers

Another approach to the nice extensions of Damien could be a multi-cast.

myArray = (myArray as NSArray).sortedArrayUsingDescriptors(tableView.sortDescriptors) as! Array

Original source: NSHipster

like image 121
Tobonaut Avatar answered Sep 28 '22 03:09

Tobonaut