Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what are the rules for spaces in swift

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.

like image 568
abhimanyuaryan Avatar asked Jul 08 '15 19:07

abhimanyuaryan


1 Answers

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

like image 88
Will M. Avatar answered Oct 16 '22 12:10

Will M.