The Swift 3 Switch Statement

From Techotopia
Jump to: navigation, search

PreviousTable of ContentsNext
Swift Flow ControlAn Overview of Swift Functions and Closures


You are reading a sample chapter from the iOS 10 App Development Essentials book.

Purchase the full iOS 10 / Swift 3 / Xcode 8 edition of this book in eBook ($19.99) or Print ($45.99) format.
iOS 10 App Development Essentials Print and eBook (ePub/PDF/Kindle) edition contains over 100 chapters. Learn more...

Buy eBook Buy Print Preview Book


In Swift 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?

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
}

You are reading a sample chapter from the iOS 10 App Development Essentials book.

Purchase the full iOS 10 / Swift 3 / Xcode 8 edition of this book in eBook ($19.99) or Print ($45.99) format.
iOS 10 App Development Essentials Print and eBook (ePub/PDF/Kindle) edition contains over 100 chapters. Learn more...

Buy eBook Buy Print Preview Book

In the above syntax outline, expression represents either a value, or an expression which 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.

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:

var value = 4

switch (value)
{
      case 0:
        println("zero")

      case 1:
        println("one")

      case 2:
        println("two")

      case 3:
        println("three")

      case 4:
        println("four")

      case 5:
        println("five")

      default:
        println("Integer out of range")
}

You are reading a sample chapter from the iOS 10 App Development Essentials book.

Purchase the full iOS 10 / Swift 3 / Xcode 8 edition of this book in eBook ($19.99) or Print ($45.99) format.
iOS 10 App Development Essentials Print and eBook (ePub/PDF/Kindle) edition contains over 100 chapters. Learn more...

Buy eBook Buy Print Preview Book

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:

var value = 1

switch (value)
{
      case 0, 1, 2:
        println("zero, one or two")

      case 3:
        println("three")

      case 4:
        println("four")

      case 5:
        println("five")

      default:
        println("Integer out of range")
}

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:

var temperature = 83

switch (temperature)
{
      case 0...49:
        println("Cold")

      case 50...79:
        println("Warm")

      case 80...110:
        println("Hot")

      default:
        println("Temperature out of range")
}

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:

var temperature = 54

switch (temperature)
{
      case 0...49 where temperature % 2 == 0:
        println("Cold and even")

      case 50...79 where temperature % 2 == 0:
        println("Warm and even")

      case 80...110 where temperature % 2 == 0:
        println("Hot and even")

      default:
        println("Temperature out of range or odd")
}

You are reading a sample chapter from the iOS 10 App Development Essentials book.

Purchase the full iOS 10 / Swift 3 / Xcode 8 edition of this book in eBook ($19.99) or Print ($45.99) format.
iOS 10 App Development Essentials Print and eBook (ePub/PDF/Kindle) edition contains over 100 chapters. Learn more...

Buy eBook Buy Print Preview Book

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:

var temperature = 10

switch (temperature)
{
      case 0...49 where temperature % 2 == 0:
        println("Cold and even")
      fallthrough

      case 50...79 where temperature % 2 == 0:
        println("Warm and even")
        fallthrough

      case 80...110 where temperature % 2 == 0:
        println("Hot and even")
        fallthrough

      default:
        println("Temperature out of range or odd")
}

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
}

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.


You are reading a sample chapter from the iOS 10 App Development Essentials book.

Purchase the full iOS 10 / Swift 3 / Xcode 8 edition of this book in eBook ($19.99) or Print ($45.99) format.
iOS 10 App Development Essentials Print and eBook (ePub/PDF/Kindle) edition contains over 100 chapters. Learn more...

Buy eBook Buy Print Preview Book



PreviousTable of ContentsNext
Swift Flow ControlAn Overview of Swift Functions and Closures