简单了解Swift语言中的break和continue语句的用法


break语句
在 C 编程语言中的 break 语句有以下两种用法:

当在循环中遇到 break 语句, 循环立即终止,程序控制继续循环语句的后面(退出循环)。

它可用于终止在switch语句(在下一章节)的情况(case)。

如果使用嵌套循环(即,一个循环在另一个循环), break语句将停止最内层循环的执行,并开始执行下一行代码块之后的代码块。

语法
在Swift 编程中的 break语句的语法如下:

复制代码 代码如下:

break


流程图

实例

复制代码 代码如下:

import Cocoa
 
var index = 10

do{
   index = index + 1
 
   if( index == 15 ){
      break
   }
   println( "Value of index is \(index)")
}while index < 20


当上述代码被编译和执行时,它产生了以下结果:

Value of index is 11
Value of index is 12
Value of index is 13
Value of index is 14

continue语句
在 Swift 编程语言中的 continue 语句告诉循环停止正在执行的语句,并在循环下一次迭代重新开始。

对于 for 循环,continue 语句使得循环的条件测试和增量部分来执行。对于 while 和 do ... while 循环,continue 语句使程序控制转到条件测试。

语法
在 Swift 中的 continue 语句的语法如下:

复制代码 代码如下:

continue


流程图

实例

复制代码 代码如下:

import Cocoa
 
var index = 10

do{
   index = index + 1
 
   if( index == 15 ){
      continue
   }
   println( "Value of index is \(index)")
}while index < 20


当上述代码被编译和执行时,它产生了以下结果:

Value of index is 11
Value of index is 12
Value of index is 13
Value of index is 14
Value of index is 16
Value of index is 17
Value of index is 18
Value of index is 19
Value of index is 20


« 
» 
快速导航

Copyright © 2016 phpStudy | 豫ICP备2021030365号-3