Mia Johansson Mia Johansson - 2 months ago 15
iOS Question

Swift: why is it updating the highscore incorrectly?

I am really stuck...any help is appreciated!!

For some reason the high score is updating when it shouldn't be. For example, the highscore will be 9 and then after finishing, the score and highschool will be, for example, 5 when the highscore should have been 9. I think it's because the current score isn't being compared to the saved highscore and is instead comparing it to the value 0 in var highscore = 0. I know that the highscore is being saved because it's displaying even after the app is closed so I don't understand why it's not comparing that saved value to the current score.

Here is my code:

var toSend = Int()
var highScore = 0

override func viewDidLoad() {
super.viewDidLoad()
let highScoreDefault = NSUserDefaults.standardUserDefaults()


if toSend > highScore
{
highScore = toSend
highScoreDefault.setValue(highScore, forKey: "Highscore")
highScoreDefault.synchronize()
}

if highScoreDefault.valueForKey("Highscore") != nil {
highScore = highScoreDefault.valueForKey("Highscore") as! NSInteger!
}


score.text = "Your Score: \(toSend)"
highScorer.text = "Your High Score: \(highScore)"
// Do any additional setup after loading the view.
}

Answer

Just swap the "if" statements and check:

if highScoreDefault.valueForKey("Highscore") != nil {
        highScore = highScoreDefault.valueForKey("Highscore") as! NSInteger!
    }

if toSend > highScore
    {
        highScore = toSend
        highScoreDefault.setValue(highScore, forKey: "Highscore")
        highScoreDefault.synchronize()
    }
Comments