这是代码,如果值(分数)大于旧值(maxscore),我试图将数据保存在plist中,但是我发现了错误...

func write() { var maxscore = NSUserDefaults.standardUserDefaults().objectForKey("chiave") as Int?

    if let test = score { // ERROR
        if maxscore < score {
            maxscore = score
        }
    }
    NSUserDefaults.standardUserDefaults().setObject(score, forKey: "chiave")
    NSUserDefaults.standardUserDefaults().synchronize()
}

Xcode的错误是
"bond value in a conditional binding must be optional type swift"

编辑新问题!我在游戏结束时编写了plist,我想在游戏开始时阅读plist,以在scoreScore中显示maxScore ...但是我遇到了一个新的错误,我正疯狂地解决它!
    func write() {

    var maxScore = NSUserDefaults.standardUserDefaults().objectForKey("chiave") as Int?
        if maxScore < score {
            maxScore = score
    }

    NSUserDefaults.standardUserDefaults().setObject(maxScore, forKey: "chiave")
    NSUserDefaults.standardUserDefaults().synchronize()
}

func read() {

    var maxScore = NSUserDefaults.standardUserDefaults().objectForKey("chiave") as Int?

    println(maxScore)  // CONSOLE RETURN -> "Optional(0)"

    labelScore.text = String(maxScore) // ERROR "Could not find an overload for init that accept the supplied argument
}

最佳答案

可以肯定的是:

var maxscore = NSUserDefaults.standardUserDefaults().objectForKey("chiave") as Int?

应该是这样的:
var maxscore = NSUserDefaults.standardUserDefaults().objectForKey("chiave") as? Int

另外,score从哪里来? Swift似乎在抱怨,因为它不是可选的。如果是这种情况,则只需执行此操作,而忽略if语句:
if maxscore < score {
    maxscore = score
}

虽然,这实际上并没有多大意义,因为在此之后您无需再执行maxscore。我想你想说的是:
if maxscore < score {
    score = maxscore
}

我会再次提到这一点,不要使用“as Int?”使用'as投射?诠释”。您不应该那样做。更改为:
if let score  = NSUserDefaults.standardUserDefaults().objectForKey("chiave") as? Int {
    labelScore.text = "\(score)"
}

10-08 19:37