OneMoreQuestion OneMoreQuestion - 2 years ago 88
Swift Question

Unexpected expression after operator in swift

I am relatively new to Swift and Playground. When experimenting in playground, I wrote a piece of Swift code to calculate the averages of 5 numbers

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

However, it keeps giving me this error "unexpected expression after operator" (see above in comments in the code). Can someone please explain why.

Answer Source

The error message is a bit misleading.

The actual error reason is the space character between count and ++.
The postfix operator must follow the operand directly without any whitespace.

Anyhow you should use always the forward compatible syntax

count += 1
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download