Swift 语言中有几种条件语句,用于根据不同的条件执行不同的代码块。以下是 Swift 中常用的条件语句:

1. if 语句:用于根据一个条件判断执行代码块。
let score = 85

if score >= 90 {
    print("优秀")
} else if score >= 80 {
    print("良好")
} else {
    print("一般")
}

2. switch 语句:用于根据多个可能的情况进行匹配,并执行相应的代码块。
let day = "Monday"

switch day {
case "Monday":
    print("星期一")
case "Tuesday":
    print("星期二")
default:
    print("其他天")
}

3. guard 语句:通常用于提前退出函数、方法或循环,如果某个条件不满足就执行一段特定代码。
func processInput(value: Int?) {
    guard let inputValue = value else {
        print("输入为空")
        return
    }
    
    // 在这里使用 inputValue 进行其他操作
    print("输入值为 \(inputValue)")
}

这些条件语句可以根据不同的需求选择使用,以便更灵活地控制程序的流程。


转载请注明出处:http://www.zyzy.cn/article/detail/6840/Swift