Jhorra Jhorra - 3 months ago 13
Swift Question

Storing values locally using NSUserDefaults

I have the following block of code

let defaults = NSUserDefaults.standardUserDefaults()
let username = self.emailText.text
let password = self.passwordText.text
defaults.setValue(username, forKey: defaultsKeys.userKey)
defaults.setValue(password, forKey: defaultsKeys.passwordKey)
var u = defaults.stringForKey(defaultsKeys.userKey)
var p = defaults.stringForKey(defaultsKeys.passwordKey)


username and password are correct when setting. However, when I pull them back u and p have the same value, and it's the password value.

I declare defaultKeys at the top of the page this way.

struct defaultsKeys {
static let userKey = ""
static let passwordKey = ""
}


I'm assuming there's a simple syntax error that I'm not seeing, because this seems like it should work.

Answer

Set different key names:

struct defaultsKeys {
    static let userKey = "userKey"
    static let passwordKey = "passwordKey"
}
Comments