Search code examples
swiftnsuserdefaults

Unable to access userDefaults with standard


I have trouble with UserDefaults.

I already tried userDefaults.standard but it's not working. The userDefeaults with standard shows an error:

"which is "Static member 'standard' cannot be used on instance of type 'UserDefaults'"

if user != nil {
    if userDefaults.standard.object
}

Static member 'standard' cannot be used on instance of type 'UserDefaults'

Why can not accept the standard with userDefaults?


Solution

  • Here is how you can work with UserDefaults.

    Get a reference to user defaults:

    let defaults = UserDefaults.standard
    

    Set an object for key "age":

    defaults.set(31, forKey: "age")
    

    Unwrap the value of the stored key. If it is nil (key does not exist), it will not enter the block.

    if let object = defaults.object(forKey: "age") {
    }