为什么 Swift 的三元运算符对空格如此挑剔?
Why is Swift's ternary operator so picky about whitespace?
问题很简单,就是找不到答案!
为什么不
return x == 0? "" : "Hello"
编译但
return x == 0 ? "" : "Hello"
是吗?
这真的很奇怪,因为所有其他运算符都不需要额外的白色 space。例如
let x = 1+1
let y = 1 + 1
相同。
我认为这与可选项有关。但是当你在变量上使用 ?
运算符时,它必须像这样使用:
let s: String? = nil
let x = s?.startIndex
我的意思是它必须跟随另一个运算符,对吗?
是的,我很确定(如您所想的那样)问题出在可选项上。
我更喜欢这样写我的三元运算符...
let num = (isTrue) ? (1) : (0)
当然,您可以选择括号中的内容,无论是否只是文字(如图所示)。
I think it has something to do with optionals.
确实如此。 operators 上的文档说:
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.
问题很简单,就是找不到答案!
为什么不
return x == 0? "" : "Hello"
编译但
return x == 0 ? "" : "Hello"
是吗?
这真的很奇怪,因为所有其他运算符都不需要额外的白色 space。例如
let x = 1+1
let y = 1 + 1
相同。
我认为这与可选项有关。但是当你在变量上使用 ?
运算符时,它必须像这样使用:
let s: String? = nil
let x = s?.startIndex
我的意思是它必须跟随另一个运算符,对吗?
是的,我很确定(如您所想的那样)问题出在可选项上。
我更喜欢这样写我的三元运算符...
let num = (isTrue) ? (1) : (0)
当然,您可以选择括号中的内容,无论是否只是文字(如图所示)。
I think it has something to do with optionals.
确实如此。 operators 上的文档说:
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.