Gabe12 Gabe12 -4 years ago 217
Swift Question

Saving and retrieving a bool with UserDefaults

I'm trying to save a bool value to UserDefaults from a UISwitch, and retrieve it in another view. However, I've tried following multiple tutorials and stack answers and none seem to work.

This is how I'm saving it:

class SettingsViewController: UITableViewController {

@IBOutlet weak var soundSwitchOutlet: UISwitch!

@IBAction func soundSwitch(_ sender: UISwitch) {

UserDefaults.standard.set(soundSwitchOutlet.isOn, forKey: "sound")

}


and this is how I'm trying to retrieve it in another view:

if let savedValue = UserDefaults.standard.bool(forKey: "sound") {
boolValue = savedValue
}

//this is inside viewDidLoad and "boolValue" was declared outside viewDidLoad//


For a reason this code is giving me errors and none of the things I've tried have worked. How can I save a bool to UserDefaults and retrieve it in another view?

Edit: I think I fixed the first part. However, the way I'm retrieving the boolean seems to be totally wrong. Also: No other stackExchange answer responds to what I'm asking, at least not in swift.

Answer Source

As Leo mentioned in the comments bool(forKey returns a non-optional Bool. If the key does not exist false is returned.

So it's simply

boolValue = UserDefaults.standard.bool(forKey: "sound")

Calling synchronize() as suggested in other answers is not needed. The framework updates the user defaults database periodically.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download