Khoury Khoury - 4 months ago 35
Swift Question

How to convert string to a different date format without error

I have a date saved in a previous version of my app in NSUserDefaults in a particular date format as string within an array.

My problem is a lot of my app has changed since that version, and now I want to convert the saved date from previous version to the date format I will be using from now on

Here is the code I am using.

if userDefault.objectForKey("day") == nil {
return
} else {
// Add the first date created from previous version
let day = userDefault.objectForKey("day") as? String
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
let date: NSDate = dateFormatter.dateFromString(day!)!


The error 'fatal error: unexpectedly found nil while unwrapping an Optional value' occurs on this line

let date: NSDate = dateFormatter.dateFromString(day!)!


Thread 1: EXC_BREAKPOINT (code=1....

Answer

You use forced unwrapping to unwrap but not sure dateFromString function return value != nil, it's case raising exception.

Trying to use ! to access a nonexistent optional value triggers a runtime error. Always make sure that an optional contains a non-nil value before using ! to force-unwrap its value.

You cannot make sure userDefault.objectForKey("day") is alway storing string of day any time. And your storing string is become with format? "yyyy-MM-dd HH:mm:ss"

You better unwrap use optional binding to make sure, the data is not nil or valid format

if let day = userDefault.objectForKey("day") as? String {
    let dateFormatter = NSDateFormatter()
    dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
    if let date = dateFormatter.dateFromString(day) {
        // convert success
        print(date)
    }
}
Comments