问题很简单,但我就是找不到答案!
为什么不
return x == 0? "" : "Hello"
编译但是
return x == 0 ? "" : "Hello"
有吗?
这真的很奇怪,因为所有其他运算符都不需要额外的空格。例如
let x = 1+1
let y = 1 + 1
是一样的。
我认为这与选项有关。但是,当您在变量上使用 ?
运算符时,必须按如下方式使用:
let s: String? = nil
let x = s?.startIndex
我的意思是它必须跟随另一个运算符,对吧?
最佳答案
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.
关于swift - 为什么 Swift 的三元运算符对空格如此挑剔?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49220101/