Swift 中的 fallthrough 语句函数

首页 / Swift入门教程 / Swift 中的 fallthrough 语句函数

SWIFT 4中的switch语句在第一个匹配case完成后立即执行里面的语句。

fallthrough - 语法

SWIFT 4中SWITCH语句的一般语法如下所示:-

无涯教程网

switch expression {
   case expression1 :
      statement(s)
      fallthrough /*  可选 */
   case expression2, expression3 :
      statement(s)
      fallthrough /* 可选 */

   default : /*  可选 */
      statement(s);
}

如果我们不使用Fallthrough语句,则程序将在执行匹配的case语句后从switch语句中出来。我们将通过以下两个示例来明确其函数。

fallthrough - 示例1

以下示例显示如何在SWIFT 4编程中使用SWITCH语句而不使用Fallthrough-

var index=10

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

编译并执行上述代码时,将生成以下结果-

Value of index is either 10 or 15

fallthrough - 示例2

以下示例显示如何在SWIFT 4编程with Fallthrough-中使用SWITCH语句

var index=10

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

编译并执行上述代码时,将生成以下结果-

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

祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)

技术教程推荐

Python核心技术与实战 -〔景霄〕

移动端自动化测试实战 -〔思寒〕

React Hooks 核心原理与实战 -〔王沛〕

全链路压测实战30讲 -〔高楼〕

超级访谈:对话毕玄 -〔毕玄〕

Go进阶 · 分布式爬虫实战 -〔郑建勋〕

结构沟通力 -〔李忠秋〕

LangChain 实战课 -〔黄佳〕

徐昊 · AI 时代的软件工程 -〔徐昊〕

好记忆不如烂笔头。留下您的足迹吧 :)