使用基本“+”运算符编译时,默认值太复杂

时间:2016-03-01 17:34:52

标签: swift compiler-errors nsuserdefaults

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") }

添加多个密钥以获得总分默认值会引发以下错误。我尝试将它们组合成对,但这不起作用。先感谢您。这是昨天发布的帖子的延续。

2 个答案:

答案 0 :(得分:1)

正如Logan的回答一样,因为你说你的复杂表达有问题"编译器错误。这应该编译:

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

}

答案 1 :(得分:0)

看起来您正在尝试将所有高分添加到一个名为totalScoreDefault的UserDefault中。如果是这样,您需要像这样设置totalScoreDefault:

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")