swift - 为什么 Swift 的三元运算符对空格如此挑剔?

标签 swift operators whitespace option-type conditional-operator

问题很简单,但我就是找不到答案!

为什么不

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/

相关文章:

swift - react 性 cocoa : wait for several firebase requests to complete (swift)

swift - Metal 中的 ASTC 纹理压缩——我应该使用什么作为每行的字节数?

php - PHP中的++$i和$i++有什么区别?

xslt - 删除 xsl 中的空白

python - 在 60 个字符后分解长字符串(添加空格)的最短方法?

HTML+CSS : Unwanted space between TDs after word-wrapping

swift - 在 Swift 中移动 UIImageView 的 UIImage 中的 UIView

swift - 泛型方法中 T 和 Self 的区别

dart - 什么是 ?? Dart 中的双问号?

rust - AddAssign 和 '+=' 运算符之间的关系