为什么三元运算符如此之快? [英] Why ternary operator in swift is so picky?

查看:126
本文介绍了为什么三元运算符如此之快?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个问题很简单,但我只是找不到答案!

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.

这篇关于为什么三元运算符如此之快?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆