在某些情况下,可以使用三元运算符来代替 if...else
语句。
在学习三元运算符之前,请确保您了解 Swift if...else 语句。
Swift 中的三元运算符
三元运算符会计算一个条件,并根据该条件执行一个代码块。其语法如下:
condition ? expression1 : expression2
在这里,三元运算符计算 condition
,并且:
- 如果
condition
为 true,则执行expression1
。 - 如果
condition
为 false,则执行expression2
。
三元运算符接受 3 个操作数(condition
、expression1
和 expression2
)。因此,它被称为 三元运算符。
示例:Swift 三元运算符
// program to check pass or fail
let marks = 60
// use of ternary operator
let result = (marks >= 40) ? "pass" : "fail"
print("You " + result + " the exam")
输出
You pass the exam.
在上面的示例中,我们使用三元运算符来检查及格或不及格。
let result = (marks >= 40) ? "pass" : "fail"
在这里,如果 marks
大于或等于 40,则将 pass
赋值给 result
。否则,将 fail
赋值给 result
。
三元运算符代替 if...else
三元运算符可以用来替换某些类型的 if...else
语句。例如:
您可以将此代码替换为
// check the number is positive or negative
let num = 15
var result = ""
if (num > 0) {
result = "Positive Number"
}
else {
result = "Negative Number"
}
print(result)
使用
// ternary operator to check the number is positive or negative
let num = 15
let result = (num > 0) ? "Positive Number" : "Negative Number"
print(result)
输出
Positive Number
这里,这两个程序给出相同的输出。但是,使用三元运算符可以使我们的代码更具可读性和整洁性。
嵌套的三元运算符
我们可以在一个三元运算符中嵌套另一个三元运算符。这在 Swift 中称为嵌套三元运算符。例如:
// program to check if a number is positive, zero, or negative
let num = 7
let result = (num == 0) ? "Zero" : ((num > 0) ? "Positive" : "Negative")
print("The number is \(result).")
输出
该数字是正数。
在上面的示例中,如果条件 num == 0
为 false
,则执行嵌套三元运算符 ((num > 0) ? "Positive" : "Negative"
。
注意: 建议不要使用嵌套三元运算符,因为它们会使代码更复杂。