Swift 中的条件语句允许根据特定条件执行不同的代码块。主要的条件语句包括 if、if-else 和 switch 语句。这些语句使得程序可以根据不同的情况作出相应的反应。
if 语句
if 语句是最基本的条件语句。它用于检查一个条件是否为真,如果条件为真,则执行紧跟在 if 语句后的代码块。
let temperatureInFahrenheit = 30
if temperatureInFahrenheit <= 32 {
print("It's very cold. Consider wearing a scarf.")
}在这个例子中,如果 temperatureInFahrenheit 的值小于或等于 32,程序将输出 "It's very cold. Consider wearing a scarf."。
if-else 语句
if-else 语句用于在满足某个条件时执行一段代码,在不满足该条件时执行另一段代码。
let temperatureInFahrenheit = 45
if temperatureInFahrenheit <= 32 {
print("It's very cold. Consider wearing a scarf.")
} else {
print("The temperature is OK.")
}在这个例子中,如果 temperatureInFahrenheit 的值小于或等于 32,程序将输出 "It's very cold. Consider wearing a scarf.";否则,程序将输出 "The temperature is OK."。
多重条件判断
可以使用 else if 语句来处理多重条件判断。
// www.javascriptcn.com code example
let temperatureInFahrenheit = 45
if temperatureInFahrenheit <= 32 {
print("It's very cold. Consider wearing a scarf.")
} else if temperatureInFahrenheit >= 86 {
print("It's really warm outside.")
} else {
print("The temperature is OK.")
}在这个例子中,程序将根据 temperatureInFahrenheit 的不同值输出不同的信息。
switch 语句
switch 语句提供了一种更简洁的方式来处理多种可能的情况。它可以匹配一个值与多个可能的模式,并执行相应的代码块。
// www.javascriptcn.com code example
let someCharacter: Character = "e"
switch someCharacter {
case "a", "e", "i", "o", "u":
print("\(someCharacter) is a vowel")
case "b", "c", "d", "f", "g", "h", "j", "k", "l", "m", "n", "p", "q", "r", "s", "t", "v", "w", "x", "y", "z":
print("\(someCharacter) is a consonant")
default:
print("\(someCharacter) is not a vowel or a consonant")
}在这个例子中,switch 语句根据字符 someCharacter 的值输出相应的信息。
匹配范围
switch 语句还可以用来匹配数字范围。
// www.javascriptcn.com code example
let age = 25
switch age {
case 0..<18:
print("You are a minor.")
case 18..<65:
print("You are an adult.")
case 65...:
print("You are a senior citizen.")
default:
print("Invalid age.")
}在这个例子中,程序会根据 age 的值输出不同的信息。
值绑定
switch 语句中的每个 case 都可以绑定到一个或多个值,这被称为值绑定。
// www.javascriptcn.com code example
let point = (1, 0)
switch point {
case (0, 0):
print("Origin")
case (_, 0):
print("On the x-axis.")
case (0, _):
print("On the y-axis.")
case (-2...2, -2...2):
print("Inside the box.")
default:
print("Outside of the box.")
}在这个例子中,switch 语句根据点的位置输出相应的信息。
where 子句
where 子句可以在 case 后面添加额外的条件,以便进一步细化匹配规则。
// www.javascriptcn.com code example
let anotherPoint = (2, 0)
switch anotherPoint {
case let (x, y) where x == y:
print("On the line x == y.")
case let (x, y) where x == -y:
print("On the line x == -y.")
case let (x, _):
print("Just on the x-axis.")
default:
print("Not matched.")
}在这个例子中,switch 语句根据点的坐标输出相应的信息。
通过这些条件语句,Swift 程序员能够灵活地控制程序流程,实现复杂的功能和逻辑。