Search code examples
swiftuserdefaults

nil Check in User Defaults (Swift 5)


I have a single image stored in UserDefaults, but until a user sets it, UserDefaults is empty. I need to check

If UserDefaults is empty and if it is, display an image.

Right now on a fresh app install until a user sets an image into UserDefaults, the app crashed.

My decode is working perfectly after I set an image in UserDefaults, just the code checking for nil is the problem.

I've only been learning swift for a month and I am stuck in this scenario.

here is my code:

 //Image Decode
 let Data = UserDefaults.standdard.object(forKey: "savedImage" as! NSData){

    if (Data as Data?) != nil {

      //display Image
       dogImageView.image = UIImage(data: Data as Data)

     }else {
         dogImageView.image = Image Literal
     }
 }

Solution

  • Use If-let to safaely unwrap optional.

        if let data = UserDefaults.standard.data(forKey: "savedImage") { // image is present 
            dogImageView.image = UIImage(data: data)
        } else { // image is not present. set a default image
            dogImageView.image = Image Literal
        }