Swift Fallthrough Statement

  Total Views : 382
  Comments : 0
  Keywords : Swift fallthrough statement to execute case statement which is next to the matching case statement with example, Use fallthrough in swift switch case to execute multiple case statements

Here we will learn what is fallthrough statement in swift and how to use swift fallthrough statement to execute multiple case statements in switch case based on our requiremetns.

Swift Fallthrough Statement

In swift fallthrough statement is used in switch case to execute case statements which is next to the matched case statements based on our requirements.

 

Generally in swift, switch case statement will stop execution whenever the first matching case statement found but if we want to execute multiple case statements in switch case then by using fallthrough keyword we can execute multiple case statements even though not matching with defined condition.

Syntax of Swift Fallthrough Statement

Following is the syntax of using swift fallthrough statement in switch case statement.

 

switch expression {

case pattern 1:

statements

fallthrough

case pattern 2:

statements

case pattern 3, pattern 4:

statements

fallthrough

default:

statements

}

If you observe above swift fallthrough statement syntax we used fallthrough in multiple switch case statements to execute case statements which are next to the matched switch case statements.

 

Now we will see how to use fallthrough statement in swift programming language with examples.

Swift Switch Fallthrough Statement Example

Following is the simple example using fallthrough in swift switch case statement to execute multiple case statements based on our requirements.

 

var name = "hello"

switch(name) {

case "hello":

print("Matched record")

fallthrough

case "two":

print("Not matched record but the fallthrough automatically picks next case statement")

default:

print("Default")

}

If you observe above swift fallthrough statement example we defined fallthrough statement in multiple switch case statements to execute case statements next to the matched case statements.

 

When we run above fallthrough statement example in swift playground we will get result like as shown below.

 

Matched record

Not matched record but the fallthrough automatically picks next case statement

This is how we can use fallthrough statements in swift programming language to execute case statements next to matched case statements based on our requirements. 

 
 

 Comments (0)

Be the first to give your valuable feedback

Leave a comment

  • Default Tutlane User