我正在尝试取得高分。我加载了高分和高分,然后将两者进行比较,看看是否应将分数设置为新的高分。当分数为负数时,它工作正常,但是当分数为正数但小于当前高分或大于高分时,似乎会将两个数字相加。它似乎也从两个中减去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

关于ios - 使用Swift保存和加载高分,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/27761423/

10-12 14:39