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

Sentry blog image

The countdown to March 31 is on.

Make the switch from app center suck less with Sentry.

Read more

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

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

Okay