Reputation: 329
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?
Upvotes: 0
Views: 181
Reputation: 36
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!
Upvotes: 0
Reputation: 14845
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
Upvotes: 1
Reputation: 131418
@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.
Upvotes: 0
Reputation: 22939
You just need to add a space between a++
and {
:
for var a = 0; a < 10; a++ {
println(a)
}
Upvotes: 1