Changes

Jump to: navigation, search

The Swift Switch Statement

28 bytes added, 04:19, 10 November 2016
Combining case Statements
In [[Swift 2 Flow Control]] we looked at how to control program execution flow using the if and else statements. Whilst 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? ==
<htmlet>ios10</htmlet>
== Combining case Statements ==
<htmlet>adsdaqbox_flow</htmlet>
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:
== Summary ==
Whilst 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.

Navigation menu