淺談Swift編程中switch與fallthrough語句的使用
在 Swift 中的 switch 語句,只要第一個(gè)匹配的情況(case) 完成執(zhí)行,而不是通過隨后的情況(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 語句,否則執(zhí)行控制都將落到下面提供匹配 case 語句隨后的 case 語句。
語法
以下是 Swift 的 switch 語句的通用語法:
switch expression {
case expression1 :
statement(s)
fallthrough /* optional */
case expression2, expression3 :
statement(s)
fallthrough /* optional */
default : /* Optional */
statement(s);
}
如果不使用 fallthrough 語句,那么程序會(huì)在 switch 語句執(zhí)行匹配 case 語句后退出來。我們將使用以下兩個(gè)例子,以說明其功能和用法。
示例 1
以下是 Swift 編程 switch 語句中不使用 fallthrough 一個(gè)例子:
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")
}
當(dāng)上述代碼被編譯和執(zhí)行時(shí),它產(chǎn)生了以下結(jié)果:
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")
}
當(dāng)上述代碼被編譯和執(zhí)行時(shí),它產(chǎn)生了以下結(jié)果:
Value of index is either 10 or 15 Value of index is 5
相關(guān)文章
Swift操作Quartz 2D進(jìn)行簡單的繪圖與坐標(biāo)變換的教程
這篇文章主要介紹了Swift操作Quartz 2D進(jìn)行簡單的繪圖與坐標(biāo)變換的教程,Quartz 2D是Core Graphics框架中的一個(gè)重要組件,經(jīng)常被Mac OS或和iOS開發(fā)者用來繪圖,需要的朋友可以參考下2016-04-04在Swift中使用Cocoa的現(xiàn)有設(shè)計(jì)模式介紹
這篇文章主要介紹了在Swift中使用Cocoa的現(xiàn)有設(shè)計(jì)模式介紹,Cocoa是蘋果公司為Mac OS X所創(chuàng)建的原生面向?qū)ο蟮腁PI,是Mac OS X上五大API之一,需要的朋友可以參考下2014-07-07swift實(shí)現(xiàn)自動(dòng)輪播圖效果(UIScrollView+UIPageControl+Timer)
這篇文章主要為大家詳細(xì)介紹了swift實(shí)現(xiàn)自動(dòng)輪播圖效果,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-09-09swift4.2實(shí)現(xiàn)新聞首頁導(dǎo)航
這篇文章主要為大家詳細(xì)介紹了swift4.2實(shí)現(xiàn)新聞首頁導(dǎo)航,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2020-07-07