Daniel
Daniel

Reputation: 7714

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?

Upvotes: 2

Views: 757

Answers (1)

Rashwan L
Rashwan L

Reputation: 38833

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

Upvotes: 5

Related Questions