Swift:通过sorting描述符sorting数组

我正在使用coredata,所以我需要sorting描述符为我的实体

例如,一个坐标实体有这个类的func:

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

我正在使用这个来做这样的CoreData的请求:

 var request = NSFetchRequest(entityName: entityName) request.sortDescriptors = T.sortDescriptors() 

但是,当我有一个坐标数组作为另一个coredata对象的属性,这是一个NSSet(即未sorting)

为了解决这个问题,我正在返回这样的坐标:

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

这感觉很丑,使用NSArray只是为了得到sortedArrayUsingDescriptors – 方法。 有没有类似的方式来直接使用sorting描述符在Swift数组,即Array<Coordinate>

谢谢!

没有内置的方法,但可以使用协议扩展来添加它们:

 extension MutableCollectionType where Index : RandomAccessIndexType, Generator.Element : AnyObject { /// Sort `self` in-place using criteria stored in a NSSortDescriptors array public mutating func sortInPlace(sortDescriptors theSortDescs: [NSSortDescriptor]) { sortInPlace { for sortDesc in theSortDescs { switch sortDesc.compareObject($0, toObject: $1) { case .OrderedAscending: return true case .OrderedDescending: return false case .OrderedSame: continue } } return false } } } extension SequenceType where Generator.Element : AnyObject { /// Return an `Array` containing the sorted elements of `source` /// using criteria stored in a NSSortDescriptors array. @warn_unused_result public func sort(sortDescriptors theSortDescs: [NSSortDescriptor]) -> [Self.Generator.Element] { return sort { for sortDesc in theSortDescs { switch sortDesc.compareObject($0, toObject: $1) { case .OrderedAscending: return true case .OrderedDescending: return false case .OrderedSame: continue } } return false } } } 

但是请注意,这只在数组元素是类而不是结构时才起作用,因为NSSortDescriptor的compareObject方法需要符合AnyObject的参数

达米安的另一个扩展方法可能是多元化的。

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

原始来源: NSHipster

@达尔尼尔的答案Swift 3版本

 extension MutableCollection where Self : RandomAccessCollection { /// Sort `self` in-place using criteria stored in a NSSortDescriptors array public mutating func sort(sortDescriptors theSortDescs: [NSSortDescriptor]) { sort { by: for sortDesc in theSortDescs { switch sortDesc.compare($0, to: $1) { case .orderedAscending: return true case .orderedDescending: return false case .orderedSame: continue } } return false } } } extension Sequence where Iterator.Element : AnyObject { /// Return an `Array` containing the sorted elements of `source` /// using criteria stored in a NSSortDescriptors array. public func sorted(sortDescriptors theSortDescs: [NSSortDescriptor]) -> [Self.Iterator.Element] { return sorted { for sortDesc in theSortDescs { switch sortDesc.compare($0, to: $1) { case .orderedAscending: return true case .orderedDescending: return false case .orderedSame: continue } } return false } } }