Swift 检查 NSDate 是否为 nil

Swift check NSDate is not nil

我从 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'
    }

将可选绑定 (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)

您正在强行将 return 值转换为 NSDate,所以这 如果该值未设置或不是 NSDate,将在运行时崩溃。 同样的情况发生在

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

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

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

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

let timeSinceQuit:Double = timeAtQuit!.timeIntervalSinceNow