简体   繁体   中英

Variable increment in for loop doesn't work

I have this Swift code:

for var a = 0; a < 10; a++{
    println(a)
}

There is an compile error on

a++{

Can anyone explain why?

If you want to use the "{" against your variable you need to use the variable name between the "+" and the "{" as per the swift documentation

for var a = 0; a < 10; ++a{
    println(a)
}

Another option as suggest ABakerSmith is to space the operators "+" and "{"

I particularly prefer the first option as it keeps my code consistent as I never use space before my "{" and also it is how is used through all apple documentation

You just need to add a space between a++ and { :

for var a = 0; a < 10; a++ {
    println(a)
}

@vacawama and ABakerSmith already told you how to fix it. The reason is that Swift uses whitespace to figure out the difference between multi-character expressions and separate expressions. It requires whitespace between symbols where languages like C don't. It still trips me up sometimes.

Also, for future reference, Swift code allows for two different For loop syntaxes.

for <initialization>; <condition>; <increment> { <statements> }

or when in an array or a collection

for <identifier> in <collection> { <statements> }

But both of them require the attention to detail on where your spaces are in the code, so be careful.

Also, since it seems like you may be rather new at Swift, I recommend checking out these awesome resources that make the journey of learning Swift a lot easier.

  • Apple's free 500 page Swift Code Reference Guide

  • Thinkster.io has a great guide for everything swift, even quick little cheat sheets to keep handy for any questions you might have in the future. When I learned swift I used this site a lot!

  • If you want to build a cool little game using swift start here!

Hope that helped! Swift is a great programming language that has a lot to offer, and I hope you have fun learning it!

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