what are the rules for spaces in swift

后端 未结 1 1418
无人及你
无人及你 2020-11-30 13:15

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

相关标签:
1条回答
  • 2020-11-30 13:16

    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

    0 讨论(0)
提交回复
热议问题