swiftoperators

Why does a function call operator need to be separated from the add operator?


In Swift, it seems that the function call operator () needs to be separated by the whitespace from the add operator +.

func f() -> String { "a" }
print(f()+ f())

The above code causes the following compile errors.

t.swift:2:12: error: expected ',' separator
print(f()+ f())
           ^
          ,
t.swift:2:10: error: '+' is not a postfix unary operator
print(f()+ f())
         ^
error: fatalError

Can you point out the language reference on this?


Solution

  • The plus in f()+ f() is being parsed as a postfix operator, according to the lexical structure.

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

    • ...

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

    • ...

    Therefore, the parser does not expect there to be another f() after f()+, and fails to parse the expression.

    It doesn't matter whether there actually is a postfix + operator available to be called. Resolving the operator happens after parsing, but the compiler has already failed at parsing in this case.