虚位以待(AD)
虚位以待(AD)
首页 > 软件编程 > Swift编程 > 浅谈Swift编程中switch与fallthrough语句的使用

浅谈Swift编程中switch与fallthrough语句的使用
类别:Swift编程   作者:码皇   来源:互联网   点击:

这篇文章主要介绍了Swift编程中switch与fallthrough语句的使用,用于基本的流程控制,需要的朋友可以参考下

在 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 15Value of index is 5

相关热词搜索: Swift switch fallthrough