.
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 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? 查看JSON文件可以看到有些课程安排到了同一天,你要做的是解决这个问题,然后把他们按照特定的顺序排序。
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!
Tuple Pattern
First, you’ll create a tuple pattern to make an array of tutorials. In the playground, add this code at the end:
1 | enum Day: Int { |
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:
1 | class Tutorial { |
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. 当day没有值的时候意味着这个课程没有安排。
Implement CustomStringConvertible
so you can easily print tutorials:
1 | extension Tutorial: CustomStringConvertible { |
Now add an array to hold the tutorials:
1 | 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:
1 | for dictionary in json { |
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
利用type-casting patterns
将字典转换为Tutorial
模型
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 | // 1 |
Here’s what’s going on, step by step:
- You switch on the key and value tuple—the tuple pattern reloaded.
- You test if the tutorial’s title is a string with the is type-casting pattern and type-cast it if the test succeeds.
- 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 theDay
enumeration’s failable initializerinit(rawValue:)
. You subtract 1 from thedayInt
variable because the enumeration’s raw values start at 0, while the days in tutorials.json start at 1. - The
switch
statement should be exhaustive, so you add adefault
case. Here you simply exit the switch with thebreak
statement.
Add this line of code at the end of the playground to print the array’s content to the console:
1 | 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:
1 | 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 | // 1 |
There’s a lot going on here, so let’s break it down:
- First you create an array of days, with every day of the week occurring exactly once.
- 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! - 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:
1 | 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 { // 1 |
Here’s what’s going on, step-by-step:
- You sort the
tutorials
array with the array’ssort(_:)
method. The method’s argument is a trailing closure which defines the sorting order of any two given tutorials in the array. It returnstrue
if you sort the tutorials in ascending order, andfalse
otherwise. - 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.
- If both tutorials are unscheduled, their days are
nil
, so you sort them in ascending order by their title using the array’scompare(_:options:)
method. 如果没有被安排时间则通过他们名字来排序 - 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.
- 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:
1 | 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:
1 | extension Day { |
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!):
1 | var order: String { |
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:
1 | func ~=(lhs: Int, rhs: Day) -> Bool { |
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 {
1 | var order: String { |
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:通过在数字上调用enumberated
就可以像字典一样通过index, tutorial
来遍历,如果是oc得需要先得到Index值然后再从数组里面取值,for in 可以省略这个步骤。
1 | NSArray *lists = @[@(1), @(2)]; |
1 | for (index, tutorial) in tutorials.enumerated() { |
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 final playground. 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 our Swift Apprentice book and 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! :]