Day 4: What is fallthrough in Swift?

Max
2 min readJan 25, 2018

--

Pic courtsey : Preview App 😆

Fun story : I was at an interview with a very reputed company, and they had this first round of objective type questions with four options. One particular question(or option you can say) took my notice was the question based on switch control flow and it had one of the option as fallthrough. I thought it was a printing error and there was not a keyword called fallthrough in Swift. Just after the interview, I realised how fool I was.

Back to business!

If you have done any programming in C styled languages, you would remember particularly one very unsafe feature in switch control flow that if we didn’t (or missed by any chance, which I did often) write break after the case ended it would just barge in the next case? (Whoa give me some privacy, bruh 😠)

Obviously Swift is more safe language, and its default nature is not that but its more concise, predictable and avoids executing multiple switch cases by mistake.

But…

If you want that(C style) feature in Swift, you need to write keyword fallthrough after every case where you need.

Example from The Swift Programming Language book

fallthrough

One last thing, and the most important

The fallthrough keyword does not check the case conditions for the switch case that it causes execution to fall into. 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.

That’s one question, see you tomorrow. If you ❤️ this article please give it a clap👏 and support my work. Also, smash that Follow icon 🟢 to get posts delivered to you on your couch. We are in this together 😇. Cheers!

Psst!👋, want to continue? Go to next article in the series or the previous one, or if you wish to start from beginning.

--

--

Max
Max

Written by Max

Senior iOS Engineer | Swift | ObjectiveC | SwiftUI | Combine |

Responses (1)