How to use Fallthrough Keyword in Swift

Hello everyone, Leo here! Today we will learn how to use the Fallthrough keyword in Swift.

We’ll explore a not-so-used keyword in swift called Fallthrough. The use case is quite limited but it’s important to know to make your Swift Language Toolbox bigger! No more talking, let’s code.

Let’s code!

 

Problem – Fallthrough Keyword in Swift

You have a switch statement that you always have to execute the cases below the match case.

Imagine that you have this piece of code for a game:

let stage = 3

switch stage {
case 1:
    print("get the weapons")
case 2:
    print("gather the party")
case 3:
    print("accept the quest!")
case 4:
    print("battle the monsters")
case 5:
    print("solve the puzzles")
default:
    print("get the loot")
}

Pretty straightforward here, you have a switch that prints the selected case, this case is “accept the quest”.

But as you can see, the stages of the game are pretty much procedural, so if want the stages to run one case after another you can just use the Fallthrough keyword for that!

Like this:

let stage = 3

switch stage {
case 1:
    print("get the weapons")
    fallthrough
case 2:
    print("gather the party")
    fallthrough
case 3:
    print("accept the quest!")
    fallthrough
case 4:
    print("battle the monsters")
    fallthrough
case 5:
    print("solve the puzzles")
    fallthrough
default:
    print("get the loot")
}

You will get:

accept the quest!

battle the monsters

solve the puzzles

get the loot

Of course, you don’t need to use fallthrough in all of your cases, you can use it only when you need it. Just to remember the fallthrough will only run the case IMMEDIATELY after the keyword so the next example will not print all the cases:

let stage = 3

switch stage {
case 1:
    print("get the weapons")
    fallthrough
case 2:
    print("gather the party")
    fallthrough
case 3:
    print("accept the quest!")
    fallthrough
case 4:
    print("battle the monsters")
    fallthrough
case 5:
    print("solve the puzzles")
default:
    print("get the loot")
}

Will print:

>accept the quest!
>battle the monsters
>solve the puzzles

And we are done!

Summary

This is the fallthrough keyword and how to use it, and I hope you enjoy it as I did! Any thoughts or feedbacks are very welcome!

That’s all my people, I hope you liked reading this article as much as I enjoyed writing it. If you want to support this blog you can Buy Me a Coffee or leave a comment saying hello. You can also sponsor posts and I’m open to freelance writing! You can reach me on LinkedIn or Twitter and send me an e-mail through the contact page.

Thanks for the reading and… That’s all folks.

Credits – image

Share this post:

Related posts

Sponsor