Ad space (banner)
๐ŸฆSwift Lessons
Lesson 14 / 68

The switch Statement

In this lesson you will learn how to branch on several values with a switch statement in Swift, which reads more clearly than a chain of if statements. This is for anyone searching for "Swift switch statement how to use".

Unlike other languages, Swift's switch needs no break and must cover every case (default catches the rest). Its pattern-matching capabilities are notably powerful.

The sample code prints a different message for case 1 through case 3 depending on day, falling back to "Other day" in default. Being able to write complex conditions such as ranges and tuples flexibly is characteristic of Swift.

A common stumbling block for beginners is the requirement to cover every case. If you expect it to compile with only a few cases as in some other languages, you get an error because there is no default clause.

In real-world development, the fallthrough keyword lets you deliberately continue into the next case, keeping the design flexible.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run Swift directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)