Swift - 编译器发出警告我没有解开一个可选项但是迫使我解开使用!而不是?

时间:2015-06-03 21:45:01

标签: swift xcode6 compiler-warnings optional-values forced-unwrapping

我的代码中出现错误,编译器发出警告,要求使用消息打开可选项

可选类型的值' NSDate?'没有打开;你的意思是使用'!'或者'?'?

我的代码是

    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
我想用吗?如果dob为nil,则解包dob以允许dobText的赋值失败。编译器的消息表明我可以使用!要么 ?但是只有我使用dob才会感到高兴!打开包装。如果我尝试使用dob?编译器抱怨并强迫我使用!

如果我强制解包dob并且它是nil,则不会导致formatter.stringFromDate(dob!)行崩溃。有人可以解释一下这里发生了什么,以及正确的方法吗

1 个答案:

答案 0 :(得分:3)

formatter.stringFromDate(someDate)NSDate作为参数,而不是可选的NSDate(NSDate?)。因此,您需要使用as!不安全地强行打开它,或者使用if let或nil合并操作符(??)安全地打开它。