Chapter    24

switch Statements

switch statements are used to execute code based on the value of a variable. To make a switch statement work, you need to define a level variable, and then you need to write a code block for each possible value of the level variable that you expect.

For this chapter, let’s assume you are writing code to help you do some geometry work. You have different shapes that you need to work with, and you want to calculate the area of each shape. You can keep track of what type of shape you are working with by using an integer variable named shape (see Listing 24-1).

Listing 24-1. shape Variable

var shape = 0

Each value of shape will correspond to a type of shape; for instance, 0 could be a square, 1 could be a parallelogram, ...

Get Swift Quick Syntax Reference now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.