-1

I'm to trying sort an array of array by date in Swift, but I'm getting this three errors:

  • Cannot infer contextual base in reference to member 'orderedAscending'
  • Value of type 'Any' has no member 'compare'
  • Cast 'Any' to 'AnyObject' or use 'as!' to force downcast to a more specific type to access members

That is the array declaration:

let array = [[5.5, 1, 2020-11-05 23:00:00 +0000], [8.0, 2, 2020-11-10 23:00:00 +0000], [5.5, 1, 2020-10-27 23:00:00 +0000]]

and that is the code that I've written to sort the array:

let sortedArray = array.sorted(by: { (($0[2]).compare($1[2]))! == .orderedAscending })
array = sortedArray

How can I solve? Thanks in advance

2
  • Does this answer your question? Sort Objects in Array by date Commented Nov 11, 2020 at 18:02
  • 2
    Using a custom struct rather than a heterogenous array could make your life much easier 😉 And the first code line doesn't compile anyway. Commented Nov 11, 2020 at 18:06

1 Answer 1

2

You need to cast the element to sort on to Date. The following cast's the last element of each sub-array to a Date and if the cast fails the sub-array will be sorted last

let sorted = array.sorted(by: { ($0.last as? Date ?? Date.distantFuture) < ($1.last as? Date ?? Date.distantPast)})
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.