Settings.bundle issue

205 Views Asked by At

I experience a problem while accessing my settings. I added a setting bundle to my Xcode project : Root.plist capture

I added the following swift code to access the name_preference key : viewDidLoad capture

1

There are 1 best solutions below

5
SwiftArchitect On BEST ANSWER

UserDefaults crash on missing preference key

Explicit unwrapping is dangerous!: what happens if the string is empty?

Bad:

let crash = settings.stringForKey("name_preference")!

Using string:

let settings = UserDefaults.standard
if let name = settings.string(forKey: "name_preference") {
    print(name)
}

Using object:

let settings = UserDefaults.standard
if let name = settings.object(forKey: "name_preference") as? String {
    print(name)
}

Test: Go to Settings and enter a string:

Settings


► Find this solution on GitHub and additional details on Swift Recipes.