xingyu zhang
xingyu zhang

Reputation: 33

Why can't I use i++ in for loop in Swift

I know the difference between i++ and ++i in Swift. As the official document said, it is better to use ++i to increment i.

But I wonder why I get a syntax error using i++ in the for loop. The code looks like this:

for var i = 0; i < 10; i++{
    println("hello")
}

However, it is OK to use either i++ or ++i in other cases. Is there any restrictions in for loop?

Upvotes: 3

Views: 1093

Answers (1)

Antonio
Antonio

Reputation: 72760

The error says that:

Operator is not a known binary operator

The cause is very simple: you need to add a blank between the operator and the opening curly brace:

i++ { 
   ^

without that, the compiler takes ++{ as a binary operator, with i and print("hello") as its arguments

The problem doesn't happen with the prefixed version of the increment operator because the i variable makes a clear separation between the ++ operator and the curly brace (letters and numbers cannot be used to define operators).

Upvotes: 7

Related Questions