0
votes

I am trying to make a high score view. I load the score and high score up and compare the two to see if the score should be set as the new high score. When the score is a negative number, it works fine, but when the number is positive but less than the current high score or bigger than the high score it seems to add the two numbers together. It also seems to subtract 1 from the two? I'm not really sure whats happening. Thanks for the help!

The high score view viewDidLoad (the only code for the view) :

override func viewDidLoad() {

    //Load Score
    let defaults: NSUserDefaults = NSUserDefaults.standardUserDefaults()
    var score = defaults.valueForKey("Score")?.integerValue ?? 0
    defaults.synchronize()
    Score = score

    //Load Highscore
    let SecondDefaults: NSUserDefaults = NSUserDefaults.standardUserDefaults()
    var highscore = SecondDefaults.valueForKey("Highscore")?.integerValue ?? 0
    SecondDefaults.synchronize()
    Highscore = highscore

    //Set Score Text
        ScoreString = String(Score)
        Scorelabel.text = ScoreString

    //Update Highscore if Score is bigger
   if Score > Highscore {

        //Set Highscore to Score
        Highscore += Score

        //Save Highscore
        let SecondDefaults: NSUserDefaults = NSUserDefaults.standardUserDefaults()
        SecondDefaults.setObject(Highscore, forKey: "Highscore")
        SecondDefaults.synchronize()

        //Set Highscore Text
        HighscoreString = String(Highscore)
        HighscoreLabel.text = HighscoreString

        NewHighscoreLabel.text = "New Highscore"
    }
   //Set Highscore Text if Score is smaller
   else if Highscore >= Score {
    HighscoreString = String(Highscore)
    HighscoreLabel.text = HighscoreString
    }
}}
1
It won’t fix the bug (though it may have led to it) but you should stick to lowercaseVariableNames at all times, rather than mixing and matching (are you using UppercaseVariableNames for member variables?). Here you have a variable named Score and another named score. This is asking for trouble. Standard in Swift is to name types starting with uppercase, and variables starting with lowercase. Since you can’t assign values to types, you can’t accidentally typo a classname for a variable, but you can typo one variable for another. - Airspeed Velocity

1 Answers

1
votes

Issue is with this code:

Highscore += Score

You are adding HighScore and Score then assigning back to HighScore. Change that to:

Highscore = Score