Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 641
xingyu zhang Avatar asked Dec 06 '25 17:12

xingyu zhang


1 Answers

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

like image 66
Antonio Avatar answered Dec 09 '25 16:12

Antonio



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!