Search code examples
swiftuserdefaults

Reduce UserDefaults Integer Value - Swift


Is there any way to reduce the UserDefaults integer key value?

This is my code to save it:

    var highScore = UserDefaults().integer(forKey: "HIGHSCORE")

How could reduce this value by a fixed integer?

So reduce by 20 etc?


Solution

  • First, obtain the old value of the high score. Then, do the arithmetic before finally saving the new value:

    let oldValue = UserDefaults.standard.integer(forKey: "HIGHSCORE")
    let newValue = oldValue - 20
    
    UserDefaults.standard.set(newValue, forKey: "HIGHSCORE")