从NSUserDefaults获取值时出错

时间:2014-12-19 14:55:30

标签: ios xcode swift plist

这是代码,如果值(得分)超过旧值(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,在分数labelScore中显示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
}

1 个答案:

答案 0 :(得分:1)

非常肯定:

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

应该是这样的:

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

此外,score来自哪里? Swift似乎在抱怨,因为它不是可选的。如果是这种情况,你可以这样做,忘记if语句:

if maxscore < score {
    maxscore = score
}

虽然,这并没有多大意义,因为在那之后你没有做任何事情。我想你想说的是:

if maxscore < score {
    score = maxscore
}

我会再次提到这一点,不要使用'as Int?'使用'as?诠释”。你不应该这样做。将您的阅读更改为:

if let score  = NSUserDefaults.standardUserDefaults().objectForKey("chiave") as? Int {
    labelScore.text = "\(score)" 
}