Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

swift case falling through

Does swift have fall through statement? e.g if I do the following

var testVar = "hello" var result = 0  switch(testVal) { case "one":     result = 1 case "two":     result = 1 default:     result = 3 } 

is it possible to have the same code executed for case "one" and case "two"?

like image 228
Bilal Syed Hussain Avatar asked Jun 04 '14 23:06

Bilal Syed Hussain


People also ask

What is fall through in Swift?

The fallthrough keyword simply causes code execution to move directly to the statements inside the next case (or default case) block, as in C's standard switch statement behaviour. Another feature I liked in the latest version of Swift is @unknown default.

Why do switch statements fall through?

Fall through is a type of error that occurs in various programming languages like C, C++, Java, Dart …etc. It occurs in switch-case statements where when we forget to add a break statement and in that case flow of control jumps to the next line.

What is a fall through with reference to switch case give an example?

Fall through condition: This condition occurs in the switch control statement when there is no break keyword mention for the particular case in the switch statement and cause execution of the cases till no break statement occurs or exit from the switch statement.

What is the use of Fallthrough?

If you want your switch statement fall through or you want C style fallthrough feature then you can use fallthrough statement. This statement is used to forcefully execute the case present next after the matched statement even though the case is not matching the specified condition.


2 Answers

Yes. You can do so as follows:

var testVal = "hello" var result = 0  switch testVal { case "one", "two":     result = 1 default:     result = 3 } 

Alternatively, you can use the fallthrough keyword:

var testVal = "hello" var result = 0  switch testVal { case "one":     fallthrough case "two":     result = 1 default:     result = 3 } 
like image 108
Cezary Wojcik Avatar answered Sep 21 '22 06:09

Cezary Wojcik


var testVar = "hello"  switch(testVar) {  case "hello":      println("hello match number 1")      fallthrough  case "two":      println("two in not hello however the above fallthrough automatically always picks the     case following whether there is a match or not! To me this is wrong")  default:      println("Default") } 
like image 26
Glenn Tisman Avatar answered Sep 21 '22 06:09

Glenn Tisman