DEV Community

Maegan Wilson
Maegan Wilson

Posted on • Updated on

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() {

    // 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

Top comments (0)