使用UserDefaults在swift中保存高分

时间:2017-06-20 20:33:30

标签: swift swift3 save saving-data userdefaults

我试图在每次玩家退出应用程序时获得高分,但是我努力让它上班,我对于我在哪里感到困惑。我犯了一个错误。

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)

2 个答案:

答案 0 :(得分:0)

以下是一个如何操作的简单示例:

let firebaseId = user.uid // Variable we want to save
UserDefaults.standard.set(firebase, forKey: "firebase") // Saving the variable with key "firebase"

现在要检索:

if let firebaseId = UserDefaults.standard.string(forKey: "firebase") {
    print("Firebase ID: \(firebase)")
}

在您的代码中,您正在检索HIGHSCORE,并且您应该检索类似gameSettings.highScore(基于我可以从您的代码中推断出来的内容)

答案 1 :(得分:0)

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

您尝试在UserDefaults中查找值,而不是通过键HIGHSCORE,而是通过ANY类型的新值HIGHSCORE。如果你想修复它,你可以这样做:

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

或者您可以使用其他名称将新值中的值展开。并且不要忘记将价值转化为合适的类型或使用

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