Pattern Matching in Swift

In this pattern matching tutorial you’ll learn how you can use pattern matching with tuples, types, wildcards, optionals, enumeration, and expressions. By Cosmin Pupăză.

Leave a rating/review
Save for later
Share

Update 9/21/16: This tutorial has been updated for Xcode 8 and Swift 3.

Pattern matching is one of the most powerful features of any programming language, because it enables you to design rules that match values against each other. This gives you flexibility and simplifies your code.

Apple makes pattern matching available in Swift, and today you’ll explore Swift’s pattern matching techniques.

The tutorial covers the following patterns:

  • Tuple pattern
  • Type-casting patterns
  • Wildcard pattern
  • Optional pattern
  • Enumeration case pattern
  • Expression pattern

To show how useful pattern matching can be, in this tutorial you’ll adopt a unique perspective: that of the editor-in-chief at raywenderlich.com! You’ll use pattern matching to help you schedule and publish tutorials on the site.

Note: This tutorial requires Xcode 8 and Swift 3 and assumes you already know the basics of Swift development. If you’re new to Swift, check out some of our other Swift tutorials first.

Getting Started

Welcome aboard, temporary editor-in-chief! Your main duties today involve scheduling tutorials for publication on the website. Start by downloading the starter playground and open starter project.playground in Xcode.

The playground contains two things:

  • The random_uniform(value:) function, which returns a random number between zero and a certain value. You’ll use this to generate random days for the schedule.
  • Boilerplate code that parses the tutorials.json file and returns its contents as an array of dictionaries. You’ll use this to extract information about the tutorials you’ll be scheduling.
Note: To learn more about JSON parsing in Swift, read our tutorial.

You don’t need to understand how all this works, but you should know the file’s structure, so go ahead and open tutorials.json from the playground’s Resources folder.

Each tutorial post you’ll be scheduling has two properties: title and scheduled day. Your team lead schedules the posts for you, assigning each tutorial a day value between 1 for Monday and 5 for Friday, or nil if leaving the post unscheduled.

You want to publish only one tutorial per day over the course of the week, but when looking over the schedule, you see that your team lead has two tutorials scheduled for the same day. You’ll need to fix the problem. Plus, you want to sort the tutorials in a particular order. How can you do all of that?

If you guessed “Using patterns!” then you’re on the right track. :]

pattern matching all the patterns!

Pattern Matching Types

Let’s get to know the kinds of patterns you’ll be working with in this tutorial.

  • Tuple patterns are used to match values of corresponding tuple types.
  • Type-casting patterns allow you to cast or match types.
  • Wildcard patterns match and ignore any kind and type of value.
  • Optional patterns are used to match optional values.
  • Enumeration case patterns match cases of existing enumeration types.
  • Expression patterns allow you to compare a given value against a given expression.

You’ll use all of these patterns in your quest to be the best editor-in-chief the site has ever seen!

Putting this guy out of a job!

Our editor in chief

Tuple Pattern

First, you’ll create a tuple pattern to make an array of tutorials. In the playground, add this code at the end:

enum Day: Int {
  case monday, tuesday, wednesday, thursday, friday, saturday, sunday
}

This creates an enumeration for the days of the week. The underlying raw type is Int, so the days are assigned raw values from 0 for Monday through 6 for Sunday.

Add the following code after the enumeration’s declaration:

class Tutorial {

  let title: String
  var day: Day?

  init(title: String, day: Day? = nil) {
    self.title = title
    self.day = day
  }
}

Here you define a tutorial type with two properties: the tutorial’s title and scheduled day. day is an optional variable because it can be nil for unscheduled tutorials.

Implement CustomStringConvertible so you can easily print tutorials:

extension Tutorial: CustomStringConvertible {
  var description: String {
    var scheduled = ", not scheduled"
    if let day = day {
      scheduled = ", scheduled on \(day)"
    }
    return title + scheduled
  }
}

Now add an array to hold the tutorials:

var tutorials: [Tutorial] = []

Next, convert the array of dictionaries from the starter project to an array of tutorials by adding the following code at the end of the playground:

for dictionary in json {
  var currentTitle = ""
  var currentDay: Day? = nil

  for (key, value) in dictionary {
    // todo: extract the information from the dictionary
  }

  let currentTutorial = Tutorial(title: currentTitle, day: currentDay)
  tutorials.append(currentTutorial)
}  

Here, you iterate over the json array with the for-in statement. For every dictionary in this array, you iterate over the key and value pairs in the dictionary by using a tuple with the for-in statement. This is the tuple pattern in action.

You add each tutorial to the array, but it is currently empty—you are going to set the tutorial’s properties in the next section with the type-casting pattern.

Type-Casting Patterns

To extract the tutorial information from the dictionary, you’ll use a type-casting pattern. Add this code inside the for (key, value) in dictionary loop, replacing the placeholder comment:

// 1
switch (key, value) {
  // 2
  case ("title", is String):
    currentTitle = value as! String
  // 3
  case ("day", let dayString as String):
    if let dayInt = Int(dayString), let day = Day(rawValue: dayInt - 1) {
      currentDay = day
  }
  // 4
  default:
    break
}

Here’s what’s going on, step by step:

  1. You switch on the key and value tuple—the tuple pattern reloaded.
  2. You test if the tutorial’s title is a string with the is type-casting pattern and type-cast it if the test succeeds.
  3. You test if the tutorial’s day is a string with the as type-casting pattern. If the test succeeds, you convert it into an Int first and then into a day of the week with the Day enumeration’s failable initializer init(rawValue:). You subtract 1 from the dayInt variable because the enumeration’s raw values start at 0, while the days in tutorials.json start at 1.
  4. The switch statement should be exhaustive, so you add a default case. Here you simply exit the switch with the break statement.

Add this line of code at the end of the playground to print the array’s content to the console:

print(tutorials)

As you can see, each tutorial in the array has its corresponding name and scheduled day properly defined now. With everything set up, you’re ready to accomplish your task: schedule only one tutorial per day for the whole week.

Cosmin Pupăză

Contributors

Cosmin Pupăză

Author

Over 300 content creators. Join our team.