-5

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?

Alexander MacLeod
  • 2,026
  • 3
  • 14
  • 22
Alex Ingram
  • 434
  • 4
  • 17
  • 3
    Are you asking how to subtract a number from a variable? And then how to store that updated value back into UserDefaults? That's some very simply stuff. Is this actually your question? – rmaddy Apr 11 '17 at 13:55
  • 1
    I know how to do this however I wasn't sure if it was the same with a userDefault value? – Alex Ingram Apr 11 '17 at 13:58
  • 3
    Why didn't you try it before posting? – rmaddy Apr 11 '17 at 14:00

2 Answers2

3

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")
Alexander MacLeod
  • 2,026
  • 3
  • 14
  • 22
0
var highScore: Int {
  get {
     return Userdefaults.standard.integer(forKey: “highScore”)
   } set {
Userdefaults.standard.set(newValue forKey: “highScore”)
   }
}

Can set high score by

highScore = 5
Kathiresan Murugan
  • 2,783
  • 3
  • 23
  • 44