3

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.

Tom Harrington
  • 69,312
  • 10
  • 146
  • 170
jacob_g
  • 674
  • 8
  • 21

1 Answers1

7

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
Adrian
  • 16,233
  • 18
  • 112
  • 180
  • Thanks, that's it. The problem was trying to retrieve it using standard.object instead of standard.value. – jacob_g Feb 06 '18 at 16:01
  • I'll add that if you're trying to get the most recent date from Core Data, storing it in `UserDefaults` might not be the best route to go. In that case, you may want to set up a `NSFetchRequest` with batch size set to 1 and fetch in descending order and use the date from the your fetched result. – Adrian Feb 06 '18 at 16:41