Swift - Compiler warns i haven't unwrapped an optional but then forces me to unwrap using ! rather than?

463 Views Asked by At

I've got an error in my code where the compiler gives a warning to unwrap an optional with the message

Value of optional type 'NSDate?' not unwrapped; did you mean to use '!' or '?'?

My code is

    let formatter = NSDateFormatter()
    let dob = currUser.valueForKey(userTextFieldKeyNames[i]) as? NSDate
    let dobText = formatter.stringFromDate(dob) //compiler says i need to unwrap dob using ! or ? ... but why am i forced to use ! rather than ? here
    field.text = dobText

I want to use ? to unwrap dob to allow the assignment to dobText to fail if dob is nil. The compiler's message indicates I can use ! or ? but it is only happy if I use dob! to unwrap. If I try to use dob? the compiler complains and forces me to use !.

If I force unwrap dob and it IS nil, won't that cause a crash in the formatter.stringFromDate(dob!) line. Can someone please explain what is going on here and the correct way to do this

1

There are 1 best solutions below

2
On BEST ANSWER

formatter.stringFromDate(someDate) takes an NSDate as a parameter and not an optional NSDate (NSDate?). Therefore, you need to either unsafely force unwrap it using as! or safely unwrap it using if let or the nil coalescing operator (??).