快速检查NSDate不是零

时间:2015-01-25 20:06:31

标签: swift nsdate

我从userDefaults获取的值可能是nil或者可能是NSDate,所以我想检查,因为我需要在该日期采取行动。我该如何正确地进行检查?

        let timeAtQuit: NSDate = (userDefaults.objectForKey("timeAtQuit") as NSDate)

    if(timeAtQuit){ Type 'NSDate' does not conform to protocol 'BooleanType'

    if(timeAtQuit != nil){ // 'NSDate' is not convertible to 'UInt8'

    another attempt:
        var timeAtQuit:NSDate? = (userDefaults.objectForKey("timeAtQuit") as NSDate)

    if(timeAtQuit != nil){
        let timeSinceQuit:Double = timeAtQuit.timeIntervalSinceNow // 'NSDate?' does not have a member named 'timeIntervalSinceNow'
    }

1 个答案:

答案 0 :(得分:10)

使用可选绑定(if let)和可选的强制转换(as?):

if let timeAtQuit = userDefaults.objectForKey("timeAtQuit") as? NSDate {
    println(timeAtQuit)
} else {
    // default value is not set or not an NSDate
}

使用

let timeAtQuit: NSDate = (userDefaults.objectForKey("timeAtQuit") as NSDate)

你强行将返回值转换为NSDate,所以这个 如果未设置值,则会在运行时崩溃NSDate

中也是如此
var timeAtQuit:NSDate? = (userDefaults.objectForKey("timeAtQuit") as NSDate)

将表达式分配给可选的NSDate?没有帮助,在评估右侧时已经发生崩溃。

处的编译器错误
let timeSinceQuit:Double = timeAtQuit.timeIntervalSinceNow
发生

因为timeAtQuit在这里是可选的,所以你必须这样做 打开它

let timeSinceQuit:Double = timeAtQuit!.timeIntervalSinceNow