Reputation: 779
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.
Upvotes: 3
Views: 1952
Reputation: 16715
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
Upvotes: 7