-1

I have a custom Post object that stores the date the post was created and using Firestore, all date objects get stored as String values.

I have a screen that displays all the posts on a tableview by retrieving the data from the database to create custom Post objects and then adding them to a custom array that stores posts

var postArray: Post

As mentioned, each post has a date stored as a string. How do I sort the array by date (string)?

Vandal
  • 708
  • 1
  • 8
  • 21

2 Answers2

0

You can compare string with > , < signs by default, as they are compared by UNICODE COLLATION ALGORITHM by default.

For more details see @Martin R 's answer https://stackoverflow.com/a/38910703/6315441

Now if all the dates are in any one format this would work

let sortedPostArray = postArray.sorted(by: { $0.date > $1.date})
Razi Tiwana
  • 1,425
  • 2
  • 13
  • 16
0

Create a computed property in Post struct/class to get date value from the string

struct Post {
    var dateString: String
    private let dateFormatter = DateFormatter()
    var date: Date? {
        dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ"//Change date format as per your string
        dateFormatter.locale = Locale(identifier: "en_US_POSIX")
        return dateFormatter.date(from: dateString)
    }
}

Then you can sort the array by this value

let sortedArray = postArray.sorted { $0.date ?? .distantFuture < $1.date ?? .distantFuture}
RajeshKumar R
  • 15,445
  • 2
  • 38
  • 70
  • 1
    Date formatters are notoriously (computationally) expensive. You really don’t want to instantiate them inside computed properties. Instantiate only one date formatter and use it repeatedly. Also, if the date is in ISO8601 format, like you suggest here, I’d consider [`ISO8601DateFormatter`](https://developer.apple.com/documentation/foundation/iso8601dateformatter). – Rob May 21 '19 at 06:05
  • @Rob I thought to use ISO8601DateFormatter but Im not sure about OP's date format – RajeshKumar R May 21 '19 at 06:09