Swift fallthrough语句介绍和用法示例

Swift 4失败声明用于模拟Swift 4切换到C / C ++样式切换的行为。在Swift 4中, switch语句在第一个匹配的情况完成后立即完成其执行, 这与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 4中Switch语句的语法

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

   default : /* Optional */
      statement(s);
}

在上面的代码中, 如果我们不使用fallthrough语句, 那么程序将在执行匹配的case语句后从switch语句中退出。

让我们看一个例子, 使之更清楚。

示例:(带有fallthrough语句的Swift 4示例)

让我们看看如何在Swift 4中使用switch语句而不使用fallthrough语句:

范例1:

var index = 4

switch index {
   case 1:
      print( "Hello Everyone")
   case 2, 3 :
      print( "This is srcmini")
   case 4 :
      print( "srcmini is an educational portal")
   default :
      print( "It is free to everyone")
}

输出

srcmini is an educational portal

范例2:

让我们看看如何在Swift 4编程中使用带有fallthrough语句的switch语句。

var index = 10
switch index {
   case 100:
      print( "Hello Everyone")
      fallthrough
   case 10, 15 :
      print( "This is srcmini")
      fallthrough
   case 5 :
      print( "srcmini is an educational portal")
   default :
      print( "It is free to everyone")
}

输出

This is srcmini
srcmini is an educational portal

微信公众号
手机浏览(小程序)

Warning: get_headers(): SSL operation failed with code 1. OpenSSL Error messages: error:14090086:SSL routines:ssl3_get_server_certificate:certificate verify failed in /mydata/web/wwwshanhubei/web/wp-content/themes/shanhuke/single.php on line 57

Warning: get_headers(): Failed to enable crypto in /mydata/web/wwwshanhubei/web/wp-content/themes/shanhuke/single.php on line 57

Warning: get_headers(https://static.shanhubei.com/qrcode/qrcode_viewid_47364.jpg): failed to open stream: operation failed in /mydata/web/wwwshanhubei/web/wp-content/themes/shanhuke/single.php on line 57
0
分享到:
没有账号? 忘记密码?