Pattern Matching in Swift

Datetime:2016-08-23 04:13:24          Topic: Swift           Share

It’s the perfect pattern match!

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 atraywenderlich.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 Swifttutorials 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 starterplayground 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 ourtutorial.

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 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!

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.

Wildcard Pattern

You use the wildcard pattern to schedule the tutorials, but you need to unschedule them all first. Add this line of code at the end of the playground:

tutorials.forEach { $0.day = nil }

This unschedules all tutorials in the array by setting their day to nil . To schedule the tutorials, add this block of code at the end of the playground:

// 1 
let days = (0...6).map { Day(rawValue: $0)! }
// 2
let randomDays = days.sorted { _ in random_uniform(value: 2) == 0 }
// 3
(0...6).forEach { tutorials[$0].day = randomDays[$0] }

There’s a lot going on here, so let’s break it down:

  1. First you create an array of days, with every day of the week occurring exactly once.
  2. You “sort” this array. The random_uniform(value:) function is used to randomly determine if an element should be sorted before or after the next element in the array. In the closure, you use an underscore to ignore the closure parameters, since you don’t need them here. Although there are technically more efficient and mathematically correct ways to randomly shuffle an array this shows the wildcard pattern in action!
  3. Finally, you assign the first seven tutorials the corresponding randomized day of the week.

Add this line of code at the end of the playground to print the scheduled tutorials to the console:

print(tutorials)

Success! You now have one tutorial scheduled for each day of the week, with no doubling up or gaps in the schedule. Great job!

Optional Pattern

The schedule has been conquered, but as editor-in-chief you also need to sort the tutorials. You’ll tackle this with optional patterns.

To sort the tutorials array in ascending order—first the unscheduled tutorials by their title and then the scheduled ones by their day—add the following block of code at the end of the playground:

// 1
tutorials.sort {
  // 2
  switch ($0.day, $1.day) {
    // 3
    case (nil, nil):
      return $0.title.compare($1.title, options: .caseInsensitive) == .orderedAscending
    // 4
    case (let firstDay?, let secondDay?):
      return firstDay.rawValue < secondDay.rawValue
    // 5
    case (nil, let secondDay?):
      return true
    case (let firstDay?, nil):
      return false
  }
}

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

  1. You sort the tutorials array with the array’s sort(_:) method. The method’s argument is a trailing closure which defines the sorting order of any two given tutorials in the array. It returns true if you sort the tutorials in ascending order, and false otherwise.
  2. You switch on a tuple made of the days of the two tutorials currently being sorted. This is the tuple pattern in action once more.
  3. If both tutorials are unscheduled, their days are nil , so you sort them in ascending order by their title using the array’s compare(_:options:) method.
  4. To test whether both tutorials are scheduled, you use an optional pattern . This pattern will only match a value that can be unwrapped. If both values can be unwrapped, you sort them in ascending order by their raw value.
  5. Again using an optional pattern, you test whether only one of the tutorials is scheduled. If so, you sort the unscheduled one before the scheduled one.

Add this line of code at the end of the playground to print the sorted tutorials:

print(tutorials)

There—now you’ve got those tutorials ordered just how you want them. You’re doing so well at this gig that you deserve a raise! Instead, however … you get more work to do.

Enumeration Case Pattern

Now let’s use the enumeration case pattern to determine the scheduled day’s name for each tutorial.

In the extension on Tutorial , you used the enumeration case names from type Day to build your custom string. Instead of remaining tied to these names, add a computed property name to Day by adding the following block of code at the end of the playground:

extension Day {
 
  var name: String {
    switch self {
      case .monday:
        return "Monday"
      case .tuesday:
        return "Tuesday"
      case .wednesday:
        return "Wednesday"
      case .thursday:
        return "Thursday"
      case .friday:
        return "Friday"
      case .saturday:
        return "Saturday"
      case .sunday:
        return "Sunday"
    }
  }
}

The switch statement in this code matches the current value ( self ) with the possible enumeration cases. This is the enumeration case pattern in action.

Quite impressive, right? Numbers are cool and all, but names are always more intuitive and so much easier to understand after all! :]

Expression Pattern

Next you’ll add a property to describe the tutorials’ scheduling order. You could use the enumeration case pattern again, as follows ( don’t add this code to your playground! ):

var order: String {
  switch self {
    case .monday:
      return "first"
    case .tuesday:
      return "second"
    case .wednesday:
      return "third"
    case .thursday:
      return "fourth"
    case .friday:
      return "fifth"
    case .saturday:
      return "sixth"
    case .sunday:
      return "seventh"
  }
}

But doing the same thing twice is for lesser editors-in-chief, right? ;] Instead, take a different approach and use the expression pattern . First you need to overload the pattern matching operator in order to change its default functionality and make it work for days as well. Add the following code at the end of the playground:

func ~=(lhs: Int, rhs: Day) -> Bool {
  return lhs == rhs.rawValue + 1
}

This code allows you to match days to integers, in this case the numbers 1 through 7. You can use this overloaded operator to write your computed property in a different way.

Add the following code at the end of the playground:

extension Tutorial {
 
  var order: String {
    guard let day = day else {
      return "not scheduled"
    }
    switch day {
      case 1:
        return "first"
      case 2:
        return "second"
      case 3:
        return "third"
      case 4:
        return "fourth"
      case 5:
        return "fifth"
      case 6:
        return "sixth"
      case 7:
        return "seventh"
      default:
        fatalError("invalid day value")
    }
  }
}

Thanks to the overloaded pattern matching operator, the day object can now be matched to integer expressions. This is the expression pattern in action.

Putting It All Together

Now that you’ve defined the day names and the tutorials’ order, you can print each tutorial’s status. Add the following block of code at the end of the playground:

for (index, tutorial) in tutorials.enumerated() {
  guard let day = tutorial.day else {
    print("\(index + 1). \(tutorial.title) is not scheduled this week.")
    continue
  }
  print("\(index + 1). \(tutorial.title) is scheduled on \(day.name). It's the \(tutorial.order) tutorial of the week.")   
}

Notice the tuple in the for-in statement? There’s the tuple pattern again!

Whew! That was a lot of work for your day as editor-in-chief, but you did a fantastic job—now you can relax and kick back by the pool.

Just kidding! An editor-in-chief’s job is never done. Back to work!

Where to Go From Here?

Here’s the finalplayground. For further experimentation, you can play around with the code in the IBM Swift Sandbox .

If you want to read more about pattern matching in Swift, check out Greg Heo’s Programming in a Swift Style video at RWDevCon 2016.

I hope you find a way to use pattern matching in your own projects. If you have any questions or comments, please join the forum discussion below! :]





About List