SWIFT 中的 continue、break、fall-through、throw 和 return 是用于控制程序流程的关键字,它们在使用上有一些区别。
1. continue:continue 关键字用于在循环中跳过当前迭代并进入下一次迭代。在循环体中遇到 continue 语句时,紧接着的语句将被跳过,直接进入下一次循环迭代。示例代码:swiftfor i in 1...5 { if i == 3 { continue } print(i)}输出结果为:
1245在上面的代码中,当 i 的值等于 3 时,continue 语句被执行,导致紧接着的 print(i) 语句被跳过,直接进入下一次循环迭代。2. break:break 关键字用于在循环或 switch 语句中提前结束当前的循环或 switch 分支。当 break 语句被执行时,程序将跳出当前的循环或 switch 语句,继续执行之后的代码。示例代码:
swiftfor i in 1...5 { if i == 3 { break } print(i)}输出结果为:
12在上面的代码中,当 i 的值等于 3 时,break 语句被执行,导致整个循环提前结束。3. fall-through:fall-through 关键字用于在 switch 语句中,使程序流程继续执行下一个 case 分支的代码块。没有 fall-through 关键字时,当匹配到一个 case 后,程序将自动跳出 switch 语句。示例代码:
swiftlet grade = "A"switch grade {case "A": print("Excellent") fallthroughcase "B": print("Good")default: print("Pass")}输出结果为:
ExcellentGood在上面的代码中,当 grade 的值为 "A" 时,程序匹配到第一个 case 分支,打印 "Excellent",然后执行 fallthrough 关键字,继续执行下一个 case 分支的代码块,打印 "Good"。4. throw:throw 关键字用于在错误处理中抛出一个错误。通过 throw 关键字,我们可以在代码中主动抛出一个实现了 Error 协议的错误类型实例。示例代码:
swiftenum CustomError: Error { case invalidInput case outOfRange}func checkNumber(_ num: Int) throws { if num < 0 { throw CustomError.invalidInput } else if num > 100 { throw CustomError.outOfRange } else { print("Number is valid") }}do { try checkNumber(50)} catch CustomError.invalidInput { print("Invalid input")} catch CustomError.outOfRange { print("Out of range")} catch { print("Unknown error")}输出结果为:
Number is valid在上面的代码中,checkNumber(_:) 函数会根据输入的数字抛出不同的错误。通过 try 关键字调用该函数,并在 do-catch 语句中捕获和处理错误。5. return:return 关键字用于结束函数的执行,并返回一个值(可选)。当程序执行到 return 语句时,函数将立即终止,并返回指定的值。示例代码:
swiftfunc divide(_ a: Int, by b: Int) -> Int { if b == 0 { return -1 } return a / b}let result = divide(10, by: 2)print(result) // 输出:5在上面的代码中,divide(_:_:) 函数用于计算两个数的商。当被除数为 0 时,函数返回 -1。否则,函数返回两个数的商。通过上面的解释和代码示例,我们可以清楚地看到 continue、break、fall-through、throw 和 return 在 SWIFT 中的不同用法和作用。这些关键字提供了丰富的控制流程的方式,能够让我们更好地控制程序的执行过程。