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
 })
3
  • 1
    Is this Swift - Sort array of objects with multiple criteria what you are looking for? Commented Aug 19, 2019 at 9: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 Commented Aug 19, 2019 at 9:02
  • Oh yes, it's perfect - I am looking for the same answer. Will have a look on it, thank you very much @MartinR. Commented Aug 19, 2019 at 9:02

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.