Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 705
jacob_g Avatar asked Jan 17 '26 12:01

jacob_g


1 Answers

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
like image 52
Adrian Avatar answered Jan 20 '26 05:01

Adrian



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!