Defaults too complex to compile with basic '+&

2019-09-09 06:15发布

func updateTotalScore() -> Int {
        var totalScoreDefault = NSUserDefaults.standardUserDefaults()

        var highScoreAB1 = defaults.integerForKey("highScoreAB1")

        var highScoreAB2 = defaults.integerForKey("highScoreAB2")

        var highScoreAB3 = defaults.integerForKey("highScoreAB3")

        var highScoreAB4 = defaults.integerForKey("highScoreAB4")
        var highScoreAB5 = defaults.integerForKey("HighScoreAB5")
        var highScoreAB6 = defaults.integerForKey("highScoreAB6")
        var highScoreAB7 = defaults.integerForKey("highScoreAB7")
    totalScoreDefault =
      (defaults.integerForKey("highScoreAB1") + defaults.integerForKey("highScoreAB2")) + (defaults.integerForKey("highScoreAB3") +   defaults.integerForKey("highScoreAB4")) + (defaults.integerForKey("highScoreAB5") + defaults.integerForKey("highScoreAB6")) + defaults.integerForKey("highScoreAB7") }

Adding multiple keys to get a total score default throws the following error. I tried grouping them together into pairs, and that did not work. Thank you in advance. This is a continuation from a post from yesterday.

2条回答
欢心
2楼-- · 2019-09-09 06:42

It looks like you are trying to add all of the highscores up into one UserDefault named totalScoreDefault. If so, you need to be setting the totalScoreDefault like so:

default.setInteger(highScoreAB1 + ... + highScoreAB7, forKey: "totalScoreDefault")

// You can also consider adding all highScores up before 
// this to make the setInteger portion look cleaner.

var totalScore = 0
for var i = 1; i < 8; i++ {
    totalScore += defaults.integerForKey("highScoreAB\(i)")
}
defaults.setInteger(totalScore, forKey: "totalScoreDefault")
查看更多
太酷不给撩
3楼-- · 2019-09-09 07:00

Just as an addition to Logan's answer, because you are saying that you have problems with "complex expression" compiler error. This should compile:

func updateTotalScore() -> Int {

           let defaults = NSUserDefaults.standardUserDefaults()

           let totalScoretDefault =
                 defaults.integerForKey("highScoreAB1") +
                 defaults.integerForKey("highScoreAB2") +
                 defaults.integerForKey("highScoreAB3") +
                 defaults.integerForKey("highScoreAB4") +
                 defaults.integerForKey("highScoreAB5") +
                 defaults.integerForKey("highScoreAB6") +
                 defaults.integerForKey("highScoreAB7")

           return totalScoretDefault

}
查看更多
登录 后发表回答