Why ternary operator in swift is so picky?

前端 未结 2 1285
日久生厌
日久生厌 2021-01-17 14:43

The question is very simple, but I just could not find the answer!

Why doesn\'t

return x == 0? \"\" : \"Hello\"

compile but

2条回答
  •  走了就别回头了
    2021-01-17 15:26

    I think it has something to do with optionals.

    It does. The documentation on operators says:

    There is one caveat to the rules [regarding whitespace around operators]. If the ! or ? predefined operator has no whitespace on the left, it is treated as a postfix operator, regardless of whether it has whitespace on the right. To use the ? as the optional-chaining operator, it must not have whitespace on the left. To use it in the ternary conditional (? :) operator, it must have whitespace around both sides.

提交回复
热议问题