Andrew Montague Andrew Montague - 1 year ago 70
Swift Question

Sorting an array in date order causes crash on device

I have an array storing different dates:

var Dates_Array = [String]()

I then have an extension that converts strings to NSDate:

extension String{
var StringToDate:NSDate {
let df = NSDateFormatter()
df.dateStyle = .LongStyle
df.timeStyle = .NoStyle
return (df.dateFromString(self))!

This is the code that sorts the array:

self.Ordered_Dates_Array = self.Dates_Array.sort { ($0 )$1 ).StringToDate) == .OrderedAscending}

In the simulator all of this code works as expected. But when I ran it on a device the app crashes, here is an image of the error message:

When I comment out the code that sorts the array everything works as expected. So what is causing my app to crash on a device but not the simulator?


This is what Dates_Array looks like:

["December 24, 2016", "September 14, 2016", "September 19, 2016", "November 19, 2016"]

My device Time Zone is London. Language = English and Calendar = Gregorian.

Answer Source

So the issue was that I had my dates written in the United States, but my region on my device is set to United Kingdom, which has a different date styles. Thanks rmaddy for your help.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download