简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM