Mike Bailey Mike Bailey - 4 months ago 12
Swift Question

NSDate from string (safely)

I am struggling to find a way to parse a NSDate from string where if it goes wrong it crash the app.

As an example, the following date would cause a crash: Wed, 12 Marc 2014 17:13:54 +00000\n\t\t\t\

I am currently using the following code:

let trimmed = unformatedDate.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet())

let dateFormatter = NSDateFormatter()

dateFormatter.dateFormat = "E, dd MMM yyyy HH:mm:ss zzzz"

if let tempDate = dateFormatter.dateFromString(trimmed) {

print(tempDate)

} else { print("We have an error with the tempCreatedDate") }


Any suggestions?

Answer

That should not cause a crash. Rather, the dateFromString method returns an optional which will be nil if the input string doesn't match the specified date format. You need to code defensively for that case, as you have done.

Where you'd crash is if you force-unwrapped the resulting optional. You're using optional binding, which is a good way to handle it.