Search code examples
iosswiftnsuserdefaults

Should I declare UserDefaults as a variable or not?


I'm worried about whether I should declare UserDefaults as a variable or not like the following code:

Pattern A

let userDefaults = UserDefaults.standard

if let userDefaults.object(forKey: "isFirstLaunch") {

}

Pattern B

if let UserDefaults.standard.bool(forKey: "isHardModeEnabled") as Bool {

}

Which is the best way and is there any difference between the two ways?


Solution

  • Both are the correct ways to use UserDefaults and it depends on your requirement like where you can use Pattern A and Pattern B like if you want to use UserDefaults.standard many places in your ViewController then you can declare

    let userDefaults = UserDefaults.standard
    

    outside your methods and access it anywhere in your UIViewController class or you can declare it as a global and you can use it any where into your project.

    But if you don't have much use of it then you can just use

    if let UserDefaults.standard.bool(forKey: "isHardModeEnabled") as Bool {
    
    }