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
You are currently viewing page 2 of 3 of this article. Click here to view the first page.

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!

Best EIC ever!

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.

No more trophies??

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.

Good job!

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

...for pattern matching

Cosmin Pupăză

Contributors

Cosmin Pupăză

Author

Over 300 content creators. Join our team.