为什么 Swift 的三元运算符对空格如此挑剔? [英] Why is Swift's ternary operator so picky about whitespace?
问题描述
问题很简单,但我就是找不到答案!
The question is very simple, but I just could not find the answer!
为什么不
return x == 0? "" : "Hello"
编译不过
return x == 0 ? "" : "Hello"
有吗?
这真的很奇怪,因为所有其他运算符都不需要额外的空格.例如
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
都一样.
我认为这与选项有关.但是当你在一个变量上使用 ?
操作符时,它必须像这样使用:
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?
推荐答案
我认为这与选项有关.
I think it has something to do with optionals.
确实如此.运营商 说:
[关于运算符周围的空格] 规则有一个警告.如果 !
或 ?
预定义运算符左侧没有空格,则将其视为后缀运算符,无论其右侧是否有空格.要将 ?
用作可选链运算符,它的左侧不能有空格.要在三元条件 (?
:
) 运算符中使用它,它的两边必须有空格.
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 的三元运算符对空格如此挑剔?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!