Daniel Daniel - 2 months ago 8
iOS Question

UserDefault new syntax in swift iOS

I'm trying to do a code like this:

the key "firstUseValue" exists?
if it does:
is valueForKey("firstUseValue") true?
print("USING FOR THE FIRST TIME")
setValueForKey("firstUseValue", false)
else
print("I HAVE BEEN USED BEFORE")
if it doesn't:
create bool for key "firstUseValue" with value true
print("USING FOR THE FIRST TIME")


but since NSUserDefault was changed to UserDefaults (in swift), I wasn't able to write a single line of code without compilation errors (that I could not understand).

How can I write this code using UserDefaults correctly?

Answer

Swift 2

// Set
NSUserDefaults.standardUserDefaults().setInteger(123, forKey: "key")
// Get
NSUserDefaults.standardUserDefaults().integerForKey("key")

Swift 3

// Set
UserDefaults.standard.set(123, forKey: "key")
// Get
UserDefaults.standard.integer(forKey: "key")

For the set you can specify what you need, Bool, String, Float etc. enter image description here