Search code examples
swiftswift3savesaving-datauserdefaults

Using UserDefaults to save a high score in swift


I"m trying to get a high score to save each time the player exits the app, but I'm struggling to get it to work and I'm confused as to where I'm making a mistake.

var gameSettings = Settings.sharedInstance
let HIGHSCORE = "HIGHSCORE"

if gameSettings.highScore < score{
        gameSettings.highScore = score

        UserDefaults.standard.set(gameSettings.highScore, forKey: HIGHSCORE)
    }

        if gameSettings.highScore >= score{
            gameSettings.score = score

    }

    let gameOverHighScore = SKLabelNode()
    gameOverHighScore.name = "gameOverHighScore"
    gameOverHighScore.fontName = "Helvetica Neue UltraLight"
    if let HIGHSCORE = UserDefaults.standard.value(forKey: HIGHSCORE) {
        gameOverHighScore.text = "HIGHSCORE : \(HIGHSCORE)M"
    }
    gameOverHighScore.fontColor = SKColor.white
    gameOverHighScore.position = CGPoint(x: 0, y: -175)
    gameOverHighScore.fontSize = 70
    gameOverHighScore.zPosition = 52
    addChild(gameOverHighScore)

Solution

  • In if let HIGHSCORE = UserDefaults.standard.value(forKey: HIGHSCORE) { gameOverHighScore.text = "HIGHSCORE : \(HIGHSCORE)M" }

    you are try find value in UserDefaults not by key HIGHSCORE, but by new value HIGHSCORE of type ANY. If you want to fix it, you can do like this:

    if let HIGHSCORE = UserDefaults.standard.value(forKey: self. self.HIGHSCORE) as! Int { gameOverHighScore.text = "HIGHSCORE : \(HIGHSCORE)M" }

    or you can unwrap value in new value with another name. And don't forget to cast value to appropriate type or use

    UserDefaults.standard.integer(forKey: self.HIGHSCORE)