-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

Onnwen
  • 204
  • 2
  • 12
  • Does this answer your question? [Sort Objects in Array by date](https://stackoverflow.com/questions/38168594/sort-objects-in-array-by-date) – pkamb Nov 11 '20 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. – vadian Nov 11 '20 at 18:06

1 Answers1

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)})
Joakim Danielson
  • 43,251
  • 5
  • 22
  • 52