0

I have an array of a custom structure called TransactionValues that has a dateAdd property with strings like "2019-02-09 03:57:22.837371", "2019-02-08 04:55:12.833307" and "2019-02-09 12:44:22.335671". I have a method where I'm sorting the array elements:

func sortByDate(array: [TransactionValues]) -> [TransactionValues] {
    print(array)
    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
    let sortedArray = array.sorted { dateFormatter.date(from: $0.dateAdd)! < dateFormatter.date(from: $1.dateAdd)! }
    print(sortedArray)
    return sortedArray
}

But it fails with error:

Fatal error: Unexpectedly found nil while unwrapping an Optional value

$0.dateAdd and $1.dateAdd aren't nil.

Any help will be appreciated.

Leo Dabus
  • 229,809
  • 59
  • 489
  • 571
Bah G
  • 29
  • 7
  • Possible duplicate of [How to Sort an Array of NSDictionary using DateTime key (Swift 4)?](https://stackoverflow.com/questions/53928563/how-to-sort-an-array-of-nsdictionary-using-datetime-key-swift-4) – TheTiger Feb 13 '19 at 06:40
  • 1
    @LeoDabus Thanks! I have retracted my close vote. – TheTiger Feb 13 '19 at 07:05
  • Possible duplicate of [What does "fatal error: unexpectedly found nil while unwrapping an Optional value" mean?](https://stackoverflow.com/questions/32170456/what-does-fatal-error-unexpectedly-found-nil-while-unwrapping-an-optional-valu) – Cristik Feb 13 '19 at 07:09

1 Answers1

3

The problem is that you are using the wrong date format when parsing your date string. The date format for "2019-02-09 03:57:22.837371" should be "yyyy-MM-dd HH:mm:ss.SSSSSS" instead of "yyyy-MM-dd HH:mm:ss". And don't forget to always set your date formatter locale to en_US_POSIX when parsing fixed date format strings:

let dateFormatter = DateFormatter()
dateFormatter.locale = Locale(identifier: "en_US_POSIX")
dateFormatter.dateFormat =  "yyyy-MM-dd HH:mm:ss.SSSSSS"

Note that ISO8601 strings are created in a way that can also be sorted without the need to be converted to date:

let sortedArray = array.sorted { $0.dateAdd < $1.dateAdd }
Leo Dabus
  • 229,809
  • 59
  • 489
  • 571