Swift 三元运算符
在本文中,您将学习使用条件运算符或三元运算符来更改程序的控制流。
在某些情况下,可以使用三元运算符替换 if…else 语句。
在学习三元运算符之前,请确保了解 Swift if…else 语句。
Swift 中的三元运算符
三元运算符计算条件,并基于该条件执行代码块。它的语法是:
condition ? expression1 : expression2
这里,三元运算符计算条件,
- 如果条件为 ture,则执行表达式 1。
- 如果条件为 false,则执行表达式 2。
三元运算符采用 3 个操作数(condition 条件、expression1 表达式 1 和 expression2 表达式 2)。因此,命名为三元运算符。
实例
// program to check pass or faillet marks = 60// use of ternary operatorlet result = (marks >= 40) ? "pass" : "fail"print("You " + result + " the exam")
结果如下:
You pass the exam.
在上面的实例中,我们使用了三元运算符来判断及格或失败。
let result = (marks >= 40) ? "pass" : "fail"
这里,若标记大于或等于 40,则为结果赋值 pass。否则,将 fail 赋值给结果。
三元运算符替换 if…else
三元运算符可用于替换某些类型的 if…else 语句。例如:
可以将下面的代码:
// check the number is positive or negativelet num = 15var result = ""if (num > 0) {result = "Positive Number"}else {result = "Negative Number"}print(result)
替换为:
// ternary operator to check the number is positive or negativelet num = 15let result = (num > 0) ? "Positive Number" : "Negative Number"print(result)
结果为:
Positive Number
在这里,两个程序给出相同的输出。然而,三元运算符的使用使我们的代码更加可读和干净。
嵌套三元运算符
我们可以在一个三元运算符中使用另一个三元运算符。这在 Swift 中称为嵌套三元运算符。例如:
// program to check if a number is positive, zero, or negativelet num = 7let result = (num == 0) ? "Zero" : ((num > 0) ? "Positive" : "Negative")print("The number is \(result).")
结果为:
The number is Positive.
在上面的实例中,我们使用了嵌套的三元运算符:
如果条件 num == 0 为 false,就会执行 ((num > 0) ? "Positive" : "Negative"。
注意:建议不要使用嵌套的三元运算符,因为它们会使我们的代码更复杂。