我在臭名昭著的SevenSwitch类中遇到了一行代码。
是这样的。。。
backgroundView.layer.cornerRadius = self.isRounded ? frame.size.height * 0.4 : 2
我不明白?
是什么,或者方程式末尾的:
是什么。 谁能解释一下这些是什么意思,以及它们是如何使用的?
运算符可以是一元,二进制或三元:
这是三元运算符对三个目标进行操作。 与C一样,Swift只有一个三元运算符,即三元条件运算符(a?b:C)。
来自Apple Documents基本操作符
三元条件运算符
三元条件运算符是一种特殊的运算符,由三部分组成,其形式为问? 答案1:答案2。 它是根据问题是否为真或为假来计算两个表达式中的一个的捷径。 如果question为true,它计算answer1并返回它的值; 否则,它将计算answer2并返回其值。
根据您的问题,如果isround
为真,那么拐角收音机就是frame.size.height
,否则就是2。
与if条件相同:
if(self.isRounded){
backgroundView.layer.cornerRadius = frame.size.height * 0.4
}
else{
backgroundView.layer.cornerRadius = 2.0
}
这是三元运算符
基本上是说“设置背景视图的角半径为帧高度的0.4倍,如果四舍五入,否则设置角半径为2”。
?
和:
是三元运算符
。 它们只是if语句的速记。
var a=b的英文翻译? c:D
,其中B
为布尔值,如果B
为true,则设置a
等于c
,如果B
为false,则设置为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
}