2017-06-20 141 views
-1

我試圖獲得高分以保存每次播放器退出應用程序,但我努力讓它工作,我很困惑我在哪裏「M犯了一個錯誤使用UserDefaults在swift中保存高分

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) 

回答

0

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

你正在嘗試通過關鍵高分發現UserDefaults值不,而是通過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) 
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)") 
} 

在你的代碼,您檢索到的高分,並且你應該檢索到類似gameSettings.highScore(根據我可以從代碼中推斷)