what are the rules for spaces in swift

老子叫甜甜 提交于 2019-11-26 11:33:00

问题


I practicing in swift\'s playground and I couldn\'t figure out why swift is too specific about where programmer should provide spaces and where not. I asked this question on many sites and chatrooms but didn\'t got any answer.

var j: Int = 34 // Right
var j:Int=23 //Wrong

Also, In class

self.variable-= 5 //Wrong. Error: Consecutive statements must be followed by ;
self.variable-=5 // Right
self.variable -= 5 // Right

;

Even this \":\" creates some issues with spaces sometimes.

I think spaces should have absolutely no effect on the code. It\'s usually just for a programmer\'s benefit. It just makes the code more readable nothing else. What\'s the best resource to read all swift rules about spaces.


回答1:


Answer to the second part of your question can be found here swift docs

The whitespace around an operator is used to determine whether an operator is used as a prefix operator, a postfix operator, or a binary operator. This behavior is summarized in the following rules:

If an operator has whitespace around both sides or around neither side, it is treated as a binary operator. As an example, the + operator in a+b and a + b is treated as a binary operator.

If an operator has whitespace on the left side only, it is treated as a prefix unary operator. As an example, the ++ operator in a ++b is treated as a prefix unary operator.

If an operator has whitespace on the right side only, it is treated as a postfix unary operator. As an example, the ++ operator in a++ b is treated as a postfix unary operator.

If an operator has no whitespace on the left but is followed immediately by a dot (.), it is treated as a postfix unary operator. As an example, the ++ operator in a++.b is treated as a postfix unary operator (a++ .b rather than a ++ .b).

etc... (read the docs for more on this)

As for the first part of your question, I didn't see any issue with either way of declaring the variables.

var j: Int = 34
var j:Int=23

The only issue with that provided code is that you declare j twice in the same scope. Try changing one of the j's to an x or y or something else.

If you were wondering about

var j:Int =10

or

var j:Int= 10

look at the rules above. = is an operator so if you were to do either of those, it would be treated as prefix or postfix, and you would get the error that prefix/postfix = is reserved

These rules are important due to the existence of operators such as the unary plus and unary minus operators. The compiler needs to be able to distinguish between a binary plus and a unary plus operator. List of operators



来源:https://stackoverflow.com/questions/31301715/what-are-the-rules-for-spaces-in-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!