Why Is Swift's Ternary Operator So Picky About Whitespace

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


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.

How can I implement a custom error throwing syntax in swift?

You can define a postfix operator which takes a throwing closure as (left) operand. ?? is already defined as an infix operator, therefore you have to choose a different name:

postfix operator <?>

postfix func <?><T>(expression: () throws -> T) -> T? {
do {
return try expression()
} catch {
print(error)
return nil
}
}

Now you can call

let result = throwingFunc<?>

or chain it with

let result = (throwingFunc<?>)?.doStuff()

Previous answer:

?? is already defined as an infix operator. For a postfix operator you have to choose a different name, for example:

postfix operator <?>

extension Result {
static postfix func <?>(value: Result) -> Success? {
switch value {
case .success(let win):
return win
case .failure(let fail):
print(fail.localizedDescription)
return nil
}
}
}

Now you can call

let res = Result(catching: throwingFunc)<?>

or chain it with

let res = (Result(catching: throwingFunc)<?>)?.doStuff()

c++ is a white space independent language, exception to the rule

Following that logic, you can use any two-character lexeme to produce such "exceptions" to the rule. For example, += and + = would be interpreted differently. I wouldn't call them exceptions though. In C++ in many contexts "no space at all" is quite different from "one or more spaces". When someone says that C++ is space-independent they usually mean that "one space" in C++ is typically the same as "more than one space".

This is reflected in the language specification, which states (see 2.1/1) that at phase 3 of translation the implementation is allowed to replace sequences of multiple whitespace characters with one space character.



Related Topics



Leave a reply



Submit