The Fallthrough keyword in Swift

Subscribe to my newsletter and never miss my upcoming articles

Hello everyone, Leo here!

Today 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.

Problem

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 of 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 print 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 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 only when like. 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

This is the fallthrough keyword, and I hope you enjoy like I did! Any thoughts or feedbacks are very welcome!

Thanks for the reading and... That's all folks!

Credit: image

No Comments Yet