当在Swift中编码时,什么是`?`或者`:` [英] What is the `?` is or the `:` at the equation when coding in Swift
问题描述
我在臭名昭着的 SevenSwitch 课程中遇到了一行代码。
I have ran into a line of code in the infamous SevenSwitch class.
以下是行...
backgroundView.layer.cornerRadius = self.isRounded ? frame.size.height * 0.4 : 2
我不明白?
或等式结束时的:
。有人可以解释这些是什么意思以及如何使用它们吗?
I don't understand what the ?
is or the :
at the end of the equation. Could someone please explain what these mean and how they are used?
推荐答案
运营商可以是一元,二元或三元:
Operators can be unary, binary, or ternary:
这是三元运营商在三个目标上运作。与C一样,Swift只有一个三元运算符,即三元条件运算符(a?b:c)。
This is Ternary operators operate on three targets. Like C, Swift has only one ternary operator, the ternary conditional operator (a ? b : c).
来自Apple Documents 基本运算符
From Apple Documents Basic Operators
三元条件运算符
三元条件运算符是一个特殊的运算符,有三个
的部分,它采用了形式问题?回答1:回答2。它是
的快捷方式,用于根据
问题是true还是false来评估两个表达式中的一个。如果问题为真,则评估answer1
并返回其值;否则,它会评估answer2并返回其
值。
The ternary conditional operator is a special operator with three parts, which takes the form question ? answer1 : answer2. It is a shortcut for evaluating one of two expressions based on whether question is true or false. If question is true, it evaluates answer1 and returns its value; otherwise, it evaluates answer2 and returns its value.
根据您的问题如果 isRound
为真,然后角落无线电 frame.size.height
否则为2。
As per your question if isRound
is true then corner radios is frame.size.height
else it's 2.
如同条件:
if(self.isRounded){
backgroundView.layer.cornerRadius = frame.size.height * 0.4
}
else{
backgroundView.layer.cornerRadius = 2.0
}
这篇关于当在Swift中编码时,什么是`?`或者`:`的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!