Ad space (banner)
๐ŸŽObjective-C Lessons
Lesson 14 / 68

The switch statement

This lesson covers branching on several conditions with Objective-C's switch statement, with the aim of organising conditions more readably than an if statement can.

A switch statement reads better than a stack of if / else if when you want to branch on a single value. Do not forget break.

The sample code prints a different message from case 1 to case 3 depending on day, falling back to default for anything else. Needing a break at the end of each case is inherited from C.

A common early stumble is forgetting that break. Leave it out and execution falls through into the next case, so it belongs at the end of every case.

In professional work, this is a frequently used construct for gathering many branches more legibly than a chain of if/else.

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

๐Ÿงช This site can't compile or run Objective-C 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)