0

I've got an array of custom objects where each object has two files date and subject - I need to write some logic that will sort these objects on a condition.

Condition - It should always sort with the date first. If multiple objects are there with the same date then those records should be sorted by its subject.

How do I do that?

I am successfully able to sort them out either using the date or subject but not sure on how to do it with this condition.

Here's the current code:

let result = results.sorted(by: { (customObject1, customObject2) -> Bool in
    if let dueDate1 = customObject1.date as Date?, let dueDate2 = customObject2.date as Date? {
        return dueDate1.compare(dueDate2 ) == .orderedDescending
    } else if let subject1 = customObject1.subject, let subject2 = customObject2.subject {
        return subject1.localizedCaseInsensitiveCompare(subject2) == .orderedAscending
    }
        return false
 })
Taimoor Suleman
  • 1,588
  • 14
  • 29
Hemang
  • 26,840
  • 19
  • 119
  • 186
  • 1
    Is this [Swift - Sort array of objects with multiple criteria](https://stackoverflow.com/questions/37603960/swift-sort-array-of-objects-with-multiple-criteria) what you are looking for? – Martin R Aug 19 '19 at 09:01
  • Maybe just add another condition in the first `if let`, something like `, dueDate1.compare(dueDate2 ) != .orderedSame`? If the dates are equal then it will trigger the `else` – Tj3n Aug 19 '19 at 09:02
  • Oh yes, it's perfect - I am looking for the same answer. Will have a look on it, thank you very much @MartinR. – Hemang Aug 19 '19 at 09:02

0 Answers0