如何获取值为 nil 的 NSDate [英] How to get NSDate with nil value
问题描述
我是 Swift 和一般编码的初学者.现在我正在尝试开发一段代码来设置每天一次的动作时间限制.
I'm a beginner in Swift and coding in general. Right now I'm trying to develop the piece of the code to set up the time limit for the action only once a day.
@IBAction func yesButtonPressed(sender: AnyObject) {
//To retrive the control date value. First time it has nil value
var controlDate = NSUserDefaults.standardUserDefaults().objectForKey("controlDate") as? NSDate
//To check current date to compare with
var currentDate = NSDate()
// To check if time interval between controlDate and currentDate is less than 1 day
var timeInterval = controlDate?.timeIntervalSinceNow
var dayInSeconds = 24 * 3600
if timeInterval < dayInSeconds {
//show alert with message "You've done it recently. Pls wait a bit"
} else {
//perfome the action
//update the value of NSUserDefaults.standardUserDefaults().objectForKey("controlDate") with current time stamp
}
}
我没有检查 controlTime 变量是否有 nil 值来捕获应用程序第一次运行,而是尝试为两种情况开发一些更短的通用代码,第一次和其余时间将 controlDate 变量保存在 UserDefaults 中.
Instead of checking if the controlTime var has nil value to catch the App first time running I was trying to develop some shorter, universal code for both case, first time and the rest times when the controlDate var will be saved in UserDefaults.
尽管如此,它还是无法正常工作((我非常感谢您的帮助!
Nevertheless it doesn't work properly (( I'd appreciate your help a lot!
推荐答案
dayInSeconds
是进行比较的错误类型.类型推断确定它应该是一个 Int
而 timeIntervalSinceNow
在幕后是一个 Double .因此,您无法准确地比较 Int 和 Double.
dayInSeconds
is the wrong type to make the comparison. Type inference is determining that it should be an Int
while timeIntervalSinceNow
is a Double under the covers. And thus, you can't definitively compare an Int and a Double with accuracy.
以这种方式创建 dayInSeconds
,以便将其类型推断为 Double 而不是 Int.
Create dayInSeconds
in this way so that it's type is inferred as a Double, rather than an Int.
var controlDate = NSUserDefaults.standardUserDefaults().objectForKey("controlDate") as? NSDate
var currentDate = NSDate()
var timeInterval = controlDate?.timeIntervalSinceNow
//*** HERES THE CHANGE***
var dayInSeconds = 24.0 * 3600
if timeInterval < dayInSeconds {
}
由于您没有尝试在 timeInterval
上调用方法,因此在这种情况下不需要可选解包.
Since you aren't attempting to call a method on timeInterval
optional unwrapping is not necessary in this case.
这篇关于如何获取值为 nil 的 NSDate的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!