userdefaults set bool swift code example

Example: store bool value in nsuserdefaults swift

struct Settings {

  fileprivate struct Keys {
      static let soundKey = "soundKey"
  }

  static var sound: Bool {
      set {
          UserDefaults.standard.set(newValue, forKey: Keys.soundKey)
      }
      get {
          if UserDefaults.standard.object(forKey: Keys.soundKey) == nil {
              // Value for sound not yet set ... Setting default ...

              UserDefaults.standard.set(true, forKey: Keys.soundKey)
              return true
          }
          return UserDefaults.standard.bool(forKey: Keys.soundKey)
      }

  }
}