Search code examples
swiftdateuserdefaults

Cannot retrieve Date object from UserDefaults Swift


I'd like to post and retrieve a Date object to UserDefaults.standard. As of now, I post the date object using UserDefaults.standard.set(firstDate, forKey: "Date") and retrieve it with inDate = UserDefaults.standard.object(forKey: "Date") where inDate is previously declared as a Date object.

When I do this, however, I get Cannot assign value of type 'Date' to type 'Any' and if I try to cast is as! a Date type the program crashes, and if I do it conditionally (as?), inDate is simply nil. Any help is greatly appreciated.


Solution

  • To set a value for a date object in UserDefaults, here's how you do it:

    let yourDate = Date() // current date
    UserDefaults.standard.set(yourDate, forKey: "YourDefaultKey")
    

    To retrieve it, you would use this:

    let yourDate = UserDefaults.standard.value(forKey: "YourDefaultKey") as! Date