[英]Swift: Sort Array by sort descriptors
我正在使用coredata所以我需要为我的实体排序描述符
例如,Coordinate-entity具有此类func:
class func sortDescriptors() -> Array<NSSortDescriptor>
{
return [NSSortDescriptor(key: "sequence", ascending: true)]
}
我在对CoreData执行获取请求时使用此方法,如下所示:
var request = NSFetchRequest(entityName: entityName)
request.sortDescriptors = T.sortDescriptors()
但是,当我有一个坐标数组作为另一个coredata对象的属性时,这是一个NSSet(即未分类)
为了解决这个问题,我将返回如下坐标:
return NSArray(array: coordinates!).sortedArrayUsingDescriptors(Coordinate.sortDescriptors()) as? Array<Coordinate>
使用NSArray只是为了获得sortedArrayUsingDescriptors
-method感觉很难sortedArrayUsingDescriptors
。 是否有类似的方法直接在Swift数组,即Array<Coordinate>
使用排序描述符?
谢谢!
Damien漂亮扩展的另一种方法可能是多播。
myArray = (myArray as NSArray).sortedArrayUsingDescriptors(tableView.sortDescriptors) as! Array
原始来源: NSHipster
没有内置方法,但您可以使用协议扩展添加它们:
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的参数
Swift 3版本@Darniel的回答
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
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.