How to get NSDate with nil value

橙三吉。 提交于 2019-12-11 20:22:18

问题


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 
    }
}

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!


回答1:


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.

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 {
}

Since you aren't attempting to call a method on timeInterval optional unwrapping is not necessary in this case.




回答2:


timeInterval is an Optional, you need to unwrap it first

if let ti = timeInterval {
    if ti < dayInSeconds {
        ...
    }
}

More on Optionals



来源:https://stackoverflow.com/questions/27130001/how-to-get-nsdate-with-nil-value

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!