Swift fallthrough語句
Swift 4的fallthrough語句用于模擬C/C++風格的switch語句中Swift 4 switch的行為。愛掏網 - it200.com在Swift 4中,switch語句在第一個匹配的case完成后就會停止執行,而不會像C和C++編程語言中那樣繼續執行后續的case。愛掏網 - it200.com
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
語句。愛掏網 - it200.com
在Swift 4中Switch
語句的語法
switch expression {
case expression1 :
statement(s)
fallthrough /* optional */
case expression2, expression3 :
statement(s)
fallthrough /* optional */
default : /* Optional */
statement(s);
}
在上面的代碼中,如果我們不使用fallthrough語句,則程序將在執行匹配的case語句后退出switch語句。愛掏網 - it200.com
我們來看一個示例來清楚地說明。愛掏網 - it200.com
示例:(具有fallthrough語句的Swift 4示例)
讓我們看看如何在Swift 4中使用switch語句而不使用fallthrough語句:
示例1
var index = 4
switch index {
case 1:
print( "Hello Everyone")
case 2,3 :
print( "This is JavaTpoint")
case 4 :
print( "JavaTpoint is an educational portal")
default :
print( "It is free to everyone")
}
輸出:
JavaTpoint is an educational portal
示例2
讓我們來看看如何在使用Swift 4編程中使用switch語句和fallthrough語句。愛掏網 - it200.com
var index = 10
switch index {
case 100:
print( "Hello Everyone")
fallthrough
case 10,15 :
print( "This is JavaTpoint")
fallthrough
case 5 :
print( "JavaTpoint is an educational portal")
default :
print( "It is free to everyone")
}
輸出:
This is JavaTpoint
JavaTpoint is an educational portal
聲明:所有內容來自互聯網搜索結果,不保證100%準確性,僅供參考。如若本站內容侵犯了原著者的合法權益,可聯系我們進行處理。