Mike Bailey Mike Bailey - 1 year ago 95
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) {


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

Any suggestions?

Answer Source

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.

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