Chapter 4. Enumerations and Pattern Matching

In Chapter 1 , Getting Started with Functional Programming in Swift, we were introduced to enumerations briefly. In this chapter, we will cover enumerations and algebraic data types in detail. Also, we will explore patterns and pattern matching in Swift.

This chapter will cover the following topics with coding examples:

  • Defining enumerations
  • Associated values
  • Raw values
  • Using enumerations
  • Algebraic data types
  • Patterns and pattern matching

Defining enumerations

In Swift, an enumeration defines a common type for related values and enables us to work with those values in a type-safe way. Values provided for each enumeration member can be a String, Character, Integer, or any floating-point type. The following example presents a simple definition of an enumeration:

enum MLSTeam {
    case montreal
    case toronto
    case newYork
    case columbus
    case losAngeles
    case seattle
}

let theTeam = MLSTeam.montreal

MLSTeam enum provides us options for MLS teams. We can choose only one of the options each time; in our example, Montreal is chosen.

Multiple cases can be defined, separated by a comma on a single line:

enum MLSTeam {
    case montreal, toronto, newYork, columbus, losAngeles, Seattle
}

var theTeam = MLSTeam.montreal

The type of theTeam is inferred when it is initialized with MLSTeam.montreal. As theTeam is already defined, we can change it with a shorter syntax as follows:

theTeam = .newYork

We were able to change theTeam with a short syntax because theTeam was already inferred and was not a constant.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset