简体   繁体   English

for循环中的变量增量不起作用

[英]Variable increment in for loop doesn't work

I have this Swift code: 我有这个Swift代码:

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 "{" 建议ABakerSmith的另一种选择是将运算符“ +”和“ {”隔开

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 我特别喜欢第一个选项,因为它可以使我的代码保持一致,因为我从来没有在“ {”之前使用空格,而且在所有Apple文档中都是这样使用的

You just need to add a space between a++ and { : 您只需要在a++{之间添加一个空格即可:

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

@vacawama and ABakerSmith already told you how to fix it. @vacawama和ABakerSmith已经告诉您如何修复它。 The reason is that Swift uses whitespace to figure out the difference between multi-character expressions and separate expressions. 原因是Swift使用空格来找出多字符表达式和单独表达式之间的差异。 It requires whitespace between symbols where languages like C don't. 它需要符号之间的空格,而C等语言则不需要。 It still trips me up sometimes. 有时它仍然使我绊倒。

Also, for future reference, Swift code allows for two different For loop syntaxes. 另外,为了将来参考,Swift代码允许使用两种不同的For循环语法。

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

or when in an array or a collection 或在arraycollection

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. 另外,由于您似乎对Swift不太熟悉,因此我建议您查看这些很棒的资源,这些资源使学习Swift的过程变得更加轻松。

  • Apple's free 500 page Swift Code Reference Guide Apple免费的500页Swift代码参考指南

  • 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. Thinkster.io为所有问题提供了出色的指南,甚至快速的小备忘单也可以为您将来遇到的任何问题提供方便。 When I learned swift I used this site a lot! 当我学会了迅捷时,我经常使用该网站!

  • If you want to build a cool little game using swift start here! 如果您想使用Swift快速构建一个很棒的小游戏,请从这里开始!

Hope that helped! 希望能有所帮助! Swift is a great programming language that has a lot to offer, and I hope you have fun learning it! Swift是一种很棒的编程语言,可以提供很多东西,我希望您学习它愉快!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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