Swift: Sort Array by sort descriptors

后端 未结 3 638
长发绾君心
长发绾君心 2020-12-30 03:51

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

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

class func sortDescriptors() -&g         


        
3条回答
  •  旧巷少年郎
    2020-12-30 04:24

    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
            }
        }
    }
    

    But note that this will work only when the array elements are classes, not structures, as NSSortDescriptor compareObject method requires arguments conforming to AnyObject

提交回复
热议问题