当在Swift中编码时,什么是`?`或者`:`

我在臭名昭着的SevenSwitch课程中遇到了一行代码。

这是线……

backgroundView.layer.cornerRadius = self.isRounded ? frame.size.height * 0.4 : 2 

我不明白是什么? 是等于或等于:等式的末尾。 有人可以解释这些是什么意思以及如何使用它们?

运算符可以是一元,二元或三元:

这是三元运营商在三个目标上运营。 与C一样,Swift只有一个三元运算符,即三元条件运算符(a?b:c)。

来自Apple Documents Basic Operators

三元条件算子

三元条件运算符是一个特殊的运算符,有三个部分,它采用forms问题? 回答1:回答2。 它是根据问题是真还是假来评估两个表达式之一的快捷方式。 如果问题为真,则评估answer1并返回其值; 否则,它会评估answer2并返回其值。

根据你的问题, 如果isRound为真,则角落无线电是frame.size.height否则它是2。

如同条件:

 if(self.isRounded){ backgroundView.layer.cornerRadius = frame.size.height * 0.4 } else{ backgroundView.layer.cornerRadius = 2.0 } 

那是三元运营商

基本上它是说“如果圆角,将背景视图的角半径设置为帧高度的0.4倍,否则将角半径设置为2”。

?:ternary operators 。 它们只是if语句的简写。

var a = b ? c : d的英文翻译var a = b ? c : d var a = b ? c : d其中b是布尔值,如果b为真,设置等于c ,如果b为假,设置为d

所以,例如,

 backgroundView.layer.cornerRadius = self.isRounded ? frame.size.height * 0.4 : 2 

可以翻译成

 if(self.isRounded){ backgroundView.layer.cornerRadius = frame.size.height * 0.4 } else{ backgroundView.layer.cornerRadius = 2 } 
Interesting Posts