hAPPy
hAPPy

Reputation: 69

Saving and Loading Up A Highscore Using Swift

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
    }
}}

Upvotes: 0

Views: 1104

Answers (1)

Midhun MP
Midhun MP

Reputation: 107131

Issue is with this code:

Highscore += Score

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

Highscore = Score

Upvotes: 1

Related Questions