swift 中运算符后的意外表达式

Unexpected expression after operator in swift

我对 Swift 和 Playground 比较陌生。在playground做实验的时候,写了一段Swift的代码,计算5个数的平均值

func avg (scores: [Int]) -> (Int){
    var avg = 0
    var total = 0
    var count = 0

    for score in scores {
        total += score
        count ++
    }   // Error: unexpected expression after operator

    avg = total/count

    return avg
}

let score = avg([10, 10, 10, 10, 10])
print(score)

但是,它一直给我这个错误"unexpected expression after operator"(见上面代码中的注释)。有人可以解释为什么。

for score in scores {
    total += score
    count ++
}   // Error: unexpected expression after operator

++ 快捷方式将在 Swift 3. 你需要这样做

for score in scores {
    total += score
    count = count + 1
}   

否则你不能在 count 和 ++

之间有一个 space

所以

count++

你可以这样试:

func average(scores: [Int]) -> Int {
    var avg = 0
    for number in numbers {
        avg += score
    }
    var  ave  = (avg)/(scores.count)
    return ave
}

而您只是将 total 除以已声明为 0 的 count。您需要数组 [Int] 的计数。所以你需要做 scores.count 给你那个数组中元素的数量。

错误信息有点误导。

真正的错误原因是count++之间的space字符。
后缀运算符必须直接跟在操作数后面,不能有任何白色space.

无论如何你应该总是使用向前兼容的语法

count += 1