Why ternary operator in swift is so picky?

匆匆过客 提交于 2019-12-04 02:56:21

问题


The question is very simple, but I just could not find the answer!

Why doesn't

return x == 0? "" : "Hello"

compile but

return x == 0 ? "" : "Hello"

does?

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

are the same.

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?


回答1:


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.




回答2:


Yes, I'm pretty sure (as you presumed) the problem is with optionals.

I prefer to write my ternary operators like this...

let num = (isTrue) ? (1) : (0)

Of course, you can choose what's in the parentheses, whether it's simply a literal (as shown) or not.



来源:https://stackoverflow.com/questions/34553318/why-ternary-operator-in-swift-is-so-picky

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!