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"))
  }
}

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.

This post is also available on DEV.