When I converting my string to NSDate
, it is returning nil
And show error :
fatal error: unexpectedly found nil while unwrapping an Optional value
for example : date = 8/9/2016 9:45:19 AM
convertDate(DateString:String) -> NSDate{
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "MM/dd/yyyy hh:mm:ss a"
let date = dateFormatter.dateFromString(DateString)
print(date) // return nil
return date!
}
You can guide what is the reason?
The problem is that your dateFormatter
can not convert the DateString
you are passing it, given the dateFormat
you have told it to use.
Therefore it gives up and returns nil
, meaning that when you've run this line:
let date = dateFormatter.dateFromString(DateString)
the value of date
is nil
Next, you take the value of date
and say "force unwrap this value and return it, I don't care if it is nil or not", as can be seen here.
return date!
As your function is expected to return a NSDate
...meaning that you guarantee that you will always return an instance of NSDate
and not nil
, and you then tell it to force unwrap something that can be (and is in this case) nil
your app keels over when you try to force unwrap date
.
In general, force unwrapping things in Swift is almost always a bad idea, unless you are absolutely sure that the value is not nil
.
So, a couple of things to consider:
How does your DateString
actually look? There must be something wrong with either that or your dateFormat
string since this value can not be parsed.
Should you always return a NSDate
? Or could you return an optional instead and let the caller of your method worry about whether your convertDate
method returns something useful or not?
Hope that gives you something to work with.