【发布时间】:2017-01-16 02:58:34
【问题描述】:
我下面的代码计算了游戏的反应时间。总反应时间以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)
}
}
}
}
【问题讨论】:
-
改进格式
标签: ios swift swift3 save nsuserdefaults