1

I am just learning to program and doing some SWIFT tutorials. I have done as much research as I could but seem to be missing some critical aspect. I have a simple game and when a player dies I want to check their score against the previously saved high. If it's higher it's to save the new score.

On a title screen the highest score is displayed.

Here is the current code I am using;

NSUserDefaults.standardUserDefaults().integerForKey("highscore")

    if score > NSUserDefaults.standardUserDefaults().integerForKey("highscore") {
        NSUserDefaults.standardUserDefaults().setInteger(score, forKey: "highscore")
        NSUserDefaults.standardUserDefaults().synchronize()
    }

    NSUserDefaults.standardUserDefaults().integerForKey("highscore")

The problem I cannot solve is simply how to print the highscore! I tried using;

hiScoreText.text = "Hi Score :  \(highscore)"

but as I guessed that isn't correct. What variable do I use or how do I "read" the highscore that has been saved?

Any advice for a new guy would be greatly appreciated.

Shruti Thombre
  • 989
  • 4
  • 11
  • 27
Frankeex
  • 449
  • 3
  • 20

2 Answers2

2

You have to store the result of NSUserDefaults.standardUserDefaults().integerForKey("highscore") inside a variable that you print.

  • Thank you so much for your help. Not only was it the solution I needed, but literally within a few minutes of me posting. Your help with this is very much appreciated. – Frankeex Oct 10 '14 at 07:08
2

I guess you forgot to save retrieved highs score to the variable:

let highscore = NSUserDefaults.standardUserDefaults().integerForKey("highscore")
Kirsteins
  • 27,065
  • 8
  • 76
  • 78
  • Thank you greatly. Again, a clear concise answer to my silly oversight... and again all in such a fast response time. Really appreciate your assistance. – Frankeex Oct 10 '14 at 06:55