Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is Swift's ternary operator so picky about whitespace?

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

Why doesn't

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

compile but

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

does?

This is really weird because all the other operators don't need an extra white space. e.g.

let x = 1+1
let y = 1 + 1

are the same.

I think it has something to do with optionals. But when you use a ? operator on a variable, it must be used like this:

let s: String? = nil
let x = s?.startIndex

I mean it must follow another operator, right?

like image 258
Sweeper Avatar asked Jan 01 '16 03:01

Sweeper


People also ask

Why ternary operator is better than if else?

Emphasis: value-selection before/after action needing values. There's a different emphasis: An if / else statement emphasises the branching first and what's to be done is secondary, while a ternary operator emphasises what's to be done over the selection of the values to do it with.

What are the three arguments of a ternary operator?

The ternary operator take three arguments: The first is a comparison argument. The second is the result upon a true comparison. The third is the result upon a false comparison.

Which is faster ternary operator or if else?

Moreover, as has been pointed out, at the byte code level there's really no difference between the ternary operator and if-then-else.

What are the advantage of using ternary operator?

Advantages of Ternary OperatorIt will shorten the code. It will improve the readability of the code. The code becomes more straightforward. Makes basic if/else logic easier to code.


1 Answers

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.

like image 66
BoltClock Avatar answered Oct 20 '22 02:10

BoltClock