使用 Swift 保存和加载高分

Saving and Loading Up A Highscore Using Swift

我正在尝试制作高分视图。我加载分数和高分并比较两者以查看是否应将分数设置为新的高分。当分数为负数时,它工作正常,但当数字为正但小于当前高分或大于高分时,它似乎将两个数字加在一起。好像也是两个减1?我不太确定发生了什么。感谢您的帮助!

高分视图viewDidLoad(视图唯一代码):

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

此代码有问题:

Highscore += Score

您正在添加 HighScoreScore,然后分配回 HighScore。将其更改为:

Highscore = Score