How to retrieve and assign a NSDate object from NSUserDefaults?

Swift 3/4/5 version using Date (type alias) instead of NSDate:

let yourDate = UserDefaults.standard.object(forKey: "yourKey") as? Date
UserDefaults.standard.set(yourDate, forKey: "yourKey")

Remember to use conditional cast operator as? to avoid crash if there is no date yet under "yourKey" in UserDefaults.


Set your date object as follows:

UserDefaults.standard.set(Date(), forKey:"yourKey")

Retrieve it using:

UserDefaults.standard.object(forKey: "yourKey") as? Date

Date will be optional of course, because it might never have been set.