Swift:按排序描述符排序数组 [英] Swift: Sort Array by sort descriptors
问题描述
我正在使用coredata,所以我需要为我的实体排序描述符
I am using coredata so I need sort descriptors for my entities
例如,一个协调中心实体有这个类func:
For example, a Coordinate-entity has this class func:
class func sortDescriptors() -> Array<NSSortDescriptor>
{
return [NSSortDescriptor(key: "sequence", ascending: true)]
}
我使用这个当向CoreData进行获取请求时:
I am using this when doing fetch-requests to CoreData like this:
var request = NSFetchRequest(entityName: entityName)
request.sortDescriptors = T.sortDescriptors()
然而,当我有一个坐标数组作为另一个coredata对象上的属性时,这是一个NSSet(Ie未排序)
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>
这感觉很丑陋,使用NSArray只是为了获得 sortedArrayUsingDescriptors
-method。有一个类似的方法,直接在Swift数组,即。
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?
谢谢!
推荐答案
没有内置的方法,但您可以使用协议扩展添加它们:
There is no built-in method for this, but you can add them using protocol extension:
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
}
}
}
<需要符合AnyObject
But note that this will work only when the array elements are classes, not structures, as NSSortDescriptor compareObject method requires arguments conforming to AnyObject
这篇关于Swift:按排序描述符排序数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!