Swift: Sort Array by sort descriptors

后端 未结 3 639
长发绾君心
长发绾君心 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:43

    Swift 3 Version of @Darniel's answer

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

提交回复
热议问题