ios – Swift:按排序描述符排序数组

前端之家收集整理的这篇文章主要介绍了ios – Swift:按排序描述符排序数组前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我使用coredata,所以我需要我的实体的排序描述符

例如,Coordinate-entity有这个类func:

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

当我对CoreData执行提取请求时,我正在使用它:

  1. var request = NSFetchRequest(entityName: entityName)
  2.  
  3. request.sortDescriptors = T.sortDescriptors()

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

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

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

哪个觉得丑陋,要使用NSArray来获取sortedArrayUsingDescriptors方法.有一种类似的方法可以直接在Swift数组上执行.阵列<坐标>通过使用排序描述符?

谢谢!

解决方法

没有内置的方法,但您可以使用协议扩展添加它们:
  1. extension MutableCollectionType where Index : RandomAccessIndexType,Generator.Element : AnyObject {
  2. /// Sort `self` in-place using criteria stored in a NSSortDescriptors array
  3. public mutating func sortInPlace(sortDescriptors theSortDescs: [NSSortDescriptor]) {
  4. sortInPlace {
  5. for sortDesc in theSortDescs {
  6. switch sortDesc.compareObject($0,toObject: $1) {
  7. case .OrderedAscending: return true
  8. case .OrderedDescending: return false
  9. case .OrderedSame: continue
  10. }
  11. }
  12. return false
  13. }
  14. }
  15. }
  16.  
  17. extension SequenceType where Generator.Element : AnyObject {
  18. /// Return an `Array` containing the sorted elements of `source`
  19. /// using criteria stored in a NSSortDescriptors array.
  20. @warn_unused_result
  21. public func sort(sortDescriptors theSortDescs: [NSSortDescriptor]) -> [Self.Generator.Element] {
  22. return sort {
  23. for sortDesc in theSortDescs {
  24. switch sortDesc.compareObject($0,toObject: $1) {
  25. case .OrderedAscending: return true
  26. case .OrderedDescending: return false
  27. case .OrderedSame: continue
  28. }
  29. }
  30. return false
  31. }
  32. }
  33. }

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

猜你在找的iOS相关文章