DEV Community

Maegan Wilson
Maegan Wilson

Posted on • Edited on

2 2

How to check if UserDefaults object is Empty

This will be a guide to check if UserDefaults has been set.
You will want to use this to make sure a value is not nil before you use it.

Here is a simple example in a ViewController class.

import UIKit

class ViewController: UIViewController {

  let theme = Themes() // custom class
  // 1. create user defaults
  let defaults = UserDefaults.standard 

  override func viewWillAppear() {
    super.viewWillAppear()

    // 2. Check if there is not an userDefaults object for theme
    if defaults.object(forKey: "theme") == nil {
      // 3. If there is not an object, then set a default. This will
      //    not be ran if there is an object.
      defaults.set("dark", forKey: "theme")
    }

    theme.setTheme(defaults.string(forKey: "theme"))
  }
}
Enter fullscreen mode Exit fullscreen mode

Link to Gist

  1. Create a constant to interact with the UserDefaults
  2. Create an if statement to check if the object does not exist.
  3. If the object does not exist, then set a default option. In the example above, I set it to dark.

There is no need to set the default option if the default object does exist because it has been set before.


If you enjoy my posts, please consider sharing it or Buying me a Coffee!

Buy Me A Coffee

AWS GenAI LIVE image

Real challenges. Real solutions. Real talk.

From technical discussions to philosophical debates, AWS and AWS Partners examine the impact and evolution of gen AI.

Learn more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay