Save dictionary in userdefaults in swift 3 with xcode 8

alionthego picture alionthego · Jun 15, 2016 · Viewed 88.5k times · Source

I am using the following code to save an object to UserDefaults (previously NSUserDefaults) using xcode 8:

let defaults = UserDefaults.standard()
defaults.set(someObject, forKey: "someObject")
print(defaults.object(forKey: "someObject"))

someObject is a dictionary and I am running on the simulator.

For some reason this is not saving the value and 'nil' is printed. Wondering if it's a simulator problem.

Answer

Jan picture Jan · Aug 12, 2016

For Swift 3

UserDefaults.standard.setValue(token, forKey: "user_auth_token")
print("\(UserDefaults.standard.value(forKey: "user_auth_token")!)")