Reputation: 716
I want to sort an array in ascending order. The dates are in string format
Optional(["2019-07-08", "2019-07-09", "2019-07-10", "2019-07-11", "2019-07-12", "2019-07-02"])
I am trying using below code but it's not working.
aryEventTime = aryEventTime.sorted(by: { ($0 as AnyObject).date.compare($1.date) == ComparisonResult.orderedAscending })
aryEventTime = aryEventTime.sorted(by: {
($0 as AnyObject).date.compare(($1 as AnyObject).date) == .orderedDescending}) as? NSMutableArray
Upvotes: 2
Views: 1178
Reputation: 24341
The array
of String
that you have is,
let arr = ["2019-07-08", "2019-07-09", "2019-07-10", "2019-07-11", "2019-07-12", "2019-07-02"]
Instead of converting the String
to Date
, you can simply sort this array using sorted()
, i.e.
let sortedArr = arr.sorted()
print(sortedArr)
Output:
["2019-07-02", "2019-07-08", "2019-07-09", "2019-07-10", "2019-07-11", "2019-07-12"]
Note: date
strings
can only be sorted
without conversion in special cases such as this one. If the strings
were in the format yyyy-dd-MM
, for example, then simple string
sorting
would not work.
Upvotes: 0
Reputation: 7171
I would not advise making it a practice doing lexicographic sorting on dates. It's simple enough just to parse these strings to proper Date
objects and sort on those:
let dateStrings = Optional(["2019-07-08", "2019-07-09", "2019-07-10", "2019-07-11", "2019-07-12", "2019-07-02"])
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd"
let sortedDates = dateStrings?.compactMap(formatter.date(from:)).sorted()
Upvotes: 3
Reputation: 716
I got the answer:
let sortedArray = aryEventTime.sorted { $0.localizedCaseInsensitiveCompare($1) == ComparisonResult.orderedAscending }
Upvotes: 1