快速检查 NSDate 不为零 [英] Swift check NSDate is not nil
问题描述
我从 userDefaults 获取一个值,该值可能为零或可能是 NSDate,因此我想检查一下,因为我需要在该日期采取行动.我将如何正确进行检查?
I'm getting a value from userDefaults which might be nil or might be an NSDate, so I want to check since I need to act on that date. How would I correctly do the check?
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?
):
Use optional binding (if let
) with an optional cast (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
,将在运行时崩溃.同样发生在
you are forcefully casting the return value to NSDate
, so this
will crash at runtime if the value is not set or not an NSDate
.
The same happens in
var timeAtQuit:NSDate? = (userDefaults.objectForKey("timeAtQuit") as NSDate)
将表达式分配给可选的 NSDate?
并没有帮助,在评估右侧时已经发生崩溃.
It does not help that the expression is assigned to an optional NSDate?
, the crash already occurs when evaluating the right-hand side.
The compiler error at
let timeSinceQuit:Double = timeAtQuit.timeIntervalSinceNow
发生是因为 timeAtQuit
在这里是可选的,所以你必须打开包装
occurs because timeAtQuit
is an optional here, so you would have to
unwrap it
let timeSinceQuit:Double = timeAtQuit!.timeIntervalSinceNow
这篇关于快速检查 NSDate 不为零的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!