浅谈Swift编程中switch与fallthrough语句的使用_技术学院_宜昌市隼壹珍商贸有限公司

您好,欢迎访问宜昌市隼壹珍商贸有限公司

400 890 5375
当前位置: 主页 > 新闻动态 > 技术学院

浅谈Swift编程中switch与fallthrough语句的使用

发布时间:2026-01-18  |  点击率:

在 Swift 中的 switch 语句,只要第一个匹配的情况(case) 完成执行,而不是通过随后的情况(case)的底部,如它在 C 和 C++ 编程语言中的那样。以下是 C 和 C++ 的 switch 语句的通用语法:
复制代码 代码如下:
switch(expression){
   case constant-expression  :
      statement(s);
      break; /* optional */
   case constant-expression  :
      statement(s);
      break; /* optional */
 
   /* you can have any number of case statements */
   default : /* Optional */
      statement(s);
}

在这里,我们需要使用 break 语句退出 case 语句,否则执行控制都将落到下面提供匹配 case 语句随后的 case 语句。

语法
以下是 Swift 的 switch 语句的通用语法:
复制代码 代码如下:
switch expression {
   case expression1  :
      statement(s)
      fallthrough /* optional */
   case expression2, expression3  :
      statement(s)
      fallthrough /* optional */
 
   default : /* Optional */
      statement(s);
}

如果不使用 fallthrough 语句,那么程序会在 switch 语句执行匹配 case 语句后退出来。我们将使用以下两个例子,以说明其功能和用法。

示例 1
以下是 Swift 编程 switch 语句中不使用 fallthrough 一个例子:
复制代码 代码如下:
import Cocoa

var index = 10

switch index {
   case 100  :
      println( "Value of index is 100")
   case 10,15  :
      println( "Value of index is either 10 or 15")
   case 5  :
      println( "Value of index is 5")
   default :
      println( "default case")
}

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

Value of index is either 10 or 15

示例 2
以下是 Swift 编程中 switch 语句带有 fallthrough 的例子:
复制代码 代码如下:
import Cocoa

var index = 10

switch index {
   case 100  :
      println( "Value of index is 100")
      fallthrough
   case 10,15  :
      println( "Value of index is either 10 or 15")
      fallthrough
   case 5  :
      println( "Value of index is 5")
   default :
      println( "default case")
}

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

Value of index is either 10 or 15
Value of index is 5

全国统一服务电话

400 890 5375

电子邮箱:879577@qq.com

公司地址:宜昌市西陵区黄河路5号三峡明珠10栋1051室

咨询微信

TEL:13680874598