如何覆盖swift3中的高分

时间:2017-01-16 02:58:34

标签: ios swift swift3 save nsuserdefaults

我的代码计算游戏的反应时间。总反应时间以totalTime计算。现在代码节省了反应时间。但是totalTime始终等于高分。因此,只保存当前分数,不会保存高分。如果代码低于当前最低totalTime,我希望代码保存最低totalTime

import UIKit
class winViewController: UIViewController {
  @IBOutlet var score2: UILabel!
  @IBOutlet var winningLabel: UILabel!
  @IBOutlet var foxMill: UILabel!
  @IBOutlet var hhighscore: UILabel!

  public var LebelText: String?
  public var LebelText2: String?
  public var LebelText3: String?
  public var LebelText4: String?

  override func viewDidLoad() {
    super.viewDidLoad()
    timeCalculation()
    loadState()
  }

  func saveScore(score: Double) {
    // Instantiate user defaults
    let userDefaults:UserDefaults = UserDefaults.standard

    // Set your score
    userDefaults.set(score, forKey: "highScore")

    // Sync user defaults
    userDefaults.synchronize()
  }

  func loadState() {
    let userDefaults = UserDefaults.standard
    let score = userDefaults.double(forKey: "highScore")
    foxMill.text = "High Score: \(score)"
  }

  func timeCalculation(){
    guard let unwrapedText = self.LebelText2 else { return }
    guard let unwrapedText2 = self.LebelText else { return }
    guard let unwrapedText3 = self.LebelText3 else { return }
    guard let unwrapedText4 = self.LebelText4 else { return }

    if let myInt = Double(unwrapedText), let myInt2 = Double(unwrapedText2), let myInt3 = Double(unwrapedText3), let myInt4 = Double(unwrapedText4) {
      var totalTime = myInt + myInt2 + myInt3 + myInt4
      self.winningLabel.text = "You won"+"\n"+"Reaction time :" + String(totalTime) + " Seconds"

      guard let highScore = UserDefaults.standard.value("highScore") as? Double else { return }

      if totalTime > highScore {
        saveScore(score: totalTime)
      }
    }
  }
}

1 个答案:

答案 0 :(得分:0)

您在视图中首先调用了timeCalculation加载了我计算您的“当前高分”并且您将其保存到用户默认值。但在你保存之前,你并没有检查它是否真的是高分。您需要在那里添加条件检查。

guard let highScore = UserDefaults.standard.value(forKey: "highScore") as? Double
else{return}
if totalTime>highScore{
    saveScore(score: totalTime)
}