1

The bottom line is to write an extension that sorts an array of NSManagedObjects by dateCreated. Or, to go from this:

let materialArray = (Array(quote.materials!) as? [Materials])?.sorted(by: { $0.dateCreated?.compare($1.dateCreated!) == .orderedDescending })

to this:

let materialArray = (Array(quote.materials!) as? [Materials])?.sortedByDate

All of my entities inherit a created date, including the one above called Materials. I'd like to write an extension to sort by that date but I'm not sure what to extend...or how. So far I have:

extension Materials
{
    func sortedByDate() -> [Materials]
    {
        return self.sorted(by: { $0.dateCreated?.compare($1.dateCreated!) == .orderedDescending })
    }
}

The biggest problem is the error stating that Materials has no member 'sorted'. Making this extension work with all entities that inherit dateCreated is the ultimate goal. Thank you.

squarehippo10
  • 1,855
  • 1
  • 15
  • 45
  • Well, you'll need to define the method for an *array* of Materials, not for a (single) Material object. – Have a look at [Generic function to sort array of class by properties](https://stackoverflow.com/questions/46599074/generic-function-to-sort-array-of-class-by-properties) for some generic solutions. – Martin R Feb 20 '19 at 20:05
  • Needing an array type should have been obvious since I am trying to sort one. As for generics, I guess I've been putting off learning about them long enough... – squarehippo10 Feb 20 '19 at 21:43

0 Answers0