The Swift Switch Statement

In Swift Control Flow, we looked at controlling program execution flow using the if and else statements. While these statement constructs work well for testing a limited number of conditions, they quickly become unwieldy when dealing with larger numbers of possible conditions. To simplify such situations, Swift has inherited the switch statement from the C programming language. Those familiar with the switch statement from other programming languages should be aware, however, that the Swift switch statement has some key differences from other implementations. In this chapter we will explore the Swift implementation of the switch statement in detail.

Why Use a switch Statement?

For a small number of logical evaluations of a value the if … else if … construct is perfectly adequate. Unfortunately, any more than two or three possible scenarios can quickly make such a construct both time-consuming to write and difficult to read. For such situations, the switch statement provides an excellent alternative.

Using the switch Statement Syntax

The syntax for a basic Swift switch statement implementation can be outlined as follows:

switch expression
{
     case match1:
          statements
 
     case match2:
          statements
    
     case match3, match4:
          statements
 
     default:
          statements
}Code language: Swift (swift)

In the above syntax outline, expression represents either a value, or an expression that returns a value. This is the value against which the switch operates.

For each possible match a case statement is provided, followed by a match value. Each potential match must be of the same type as the governing expression. Following on from the case line are the Swift statements that are to be executed in the event of the value matching the case condition.

 

 

You are reading a sample chapter from an old edition of iOS App Development Essentials.

Purchase the fully updated iOS 18 App Development Essentials book.

The full book contains 71 chapters, over 612 pages of in-depth information, downloadable source code, and access to over 50 SwiftUI knowledge test quizzes.

Learn more.

Preview  Buy eBook 

 

Finally, the default section of the construct defines what should happen if none of the case statements present a match to the expression.

A Swift switch Statement Example

With the above information in mind, we may now construct a simple switch statement:

let value = 4
 
switch (value)
{
      case 0:
        print("zero")
 
      case 1:
        print("one")
 
      case 2:
        print("two")
 
      case 3:
        print("three")
 
      case 4:
        print("four")
 
      case 5:
        print("five")
 
      default:
        print("Integer out of range")
}Code language: Swift (swift)

Combining case Statements

In the above example, each case had its own set of statements to execute. Sometimes a number of different matches may require the same code to be executed. In this case, it is possible to group case matches together with a common set of statements to be executed when a match for any of the cases is found. For example, we can modify the switch construct in our example so that the same code is executed regardless of whether the value is 0, 1 or 2:

let value = 1
 
switch (value)
{
      case 0, 1, 2:
        print("zero, one or two")
 
      case 3:
        print("three")
 
      case 4:
        print("four")
 
      case 5:
        print("five")
 
      default:
        print("Integer out of range")
}Code language: Swift (swift)

Range Matching in a switch Statement

The case statements within a switch construct may also be used to implement range matching. The following switch statement, for example, checks a temperature value for matches within three number ranges:

let temperature = 83
 
switch (temperature)
{
      case 0...49:
        print("Cold")
 
      case 50...79:
        print("Warm")
 
      case 80...110:
        print("Hot")
 
      default:
        print("Temperature out of range")
}Code language: Swift (swift)

Using the where statement

The where statement may be used within a switch case match to add additional criteria required for a positive match. The following switch statement, for example, checks not only for the range in which a value falls, but also whether the number is odd or even:

 

 

You are reading a sample chapter from an old edition of iOS App Development Essentials.

Purchase the fully updated iOS 18 App Development Essentials book.

The full book contains 71 chapters, over 612 pages of in-depth information, downloadable source code, and access to over 50 SwiftUI knowledge test quizzes.

Learn more.

Preview  Buy eBook 

 

let temperature = 54
 
switch (temperature)
{
      case 0...49 where temperature % 2 == 0:
        print("Cold and even")
 
      case 50...79 where temperature % 2 == 0:
        print("Warm and even")
 
      case 80...110 where temperature % 2 == 0:
        print("Hot and even")
 
      default:
        print("Temperature out of range or odd")
}Code language: Swift (swift)

Fallthrough

Those familiar with switch statements in other languages such as C and Objective-C will notice that it is no longer necessary to include a break statement after each case declaration. Unlike other languages, Swift automatically breaks out of the statement when a matching case condition is met. The fallthrough effect of other switch implementations (whereby the execution path continues through the remaining case statements) can be emulated using the fallthrough statement:

let temperature = 10
 
switch (temperature)
{
      case 0...49 where temperature % 2 == 0:
        print("Cold and even")
        fallthrough
 
      case 50...79 where temperature % 2 == 0:
        print("Warm and even")
        fallthrough
 
      case 80...110 where temperature % 2 == 0:
        print("Hot and even")
        fallthrough
 
      default:
        print("Temperature out of range or odd")
}Code language: Swift (swift)

Although break is less commonly used in Swift switch statements, it is useful when no action needs to be taken for the default case. For example:

.
.
default:
     break
}Code language: Swift (swift)

Summary

While the if.. else.. construct serves as a good decision-making option for small numbers of possible outcomes, this approach can become unwieldy in more complex situations. As an alternative method for implementing flow control logic in Swift when many possible outcomes exist as the result of an evaluation, the switch statement invariably makes a more suitable option. As outlined in this chapter, however, developers familiar with switch implementations from other programming languages should be aware of some subtle differences in the way that the Swift switch statement works.


Categories