Search code examples
swiftxcodeaction

found nil while unwrapping in UserDefaults


I want to save the Date to userDefaults.

Button(action: {

                var date = Date()
                if date != nil{
                    date = UserDefaults.standard.object(forKey: "myDate") as! Date
                }
                print(date)
            }) {
            ........(design stuff)
            }

Tested also: let date = UserDefaults.standard.object(forKey: "myDate") as! Date

But I always get Unexpectedly found nil while unwrapping an Optional value.


Solution

  • Check if the object is available in UserDefaults before you force cast it using !. Always cast optionals safely using if let or guard let.

    To save the date:

    UserDefaults.standard.set(myDate, forKey: "myDate")
    

    To retrieve the date:

    if let object = UserDefaults.standard.object(forKey: "myDate") as? Date {
        date = object
    } else {
        print("No object for key myDate in UserDefaults")
    }