---
title: "#22: Pattern Matching 🔠🔢"
url: https://littlebitesofcocoa.com/22-pattern-matching
author: Jake Marsh
published: 2015-06-23
topics: ["Swift","Techniques"]
description: "Patterns are one of the most powerful parts of Swift. Let's look at a few examples of cool things you can do with pattern matching."
---

# #22: Pattern Matching 🔠🔢

By Jake Marsh, June 23, 2015. HTML: https://littlebitesofcocoa.com/22-pattern-matching

**Patterns** are one of the most powerful parts of Swift. Let's look at a few examples of cool things you can do with pattern matching.

## Ranges

``` swift
let since: NSTimeInterval = 127 // 2 minutes, 7 seconds

switch since {
    case (0...10): print("just now")
    case (10...60): print("a minute ago")
    default: print("\(since) seconds")
}
```

## Enums

``` swift
enum Result {
  case Success
  case Error(String)
}

let r = Result.Success

switch r {
  case .Success: print("Yay!")
  case .Error(let err): print("Boo: \(err)")
}
```

## Types

``` swift
let something = Product()

switch something {
    case is Product: print("Found a product")
    case let person as Person: print("Found a person: \(person.name)")
    default: print("Found an unknown thing.")
}
```

## Where

``` swift
let contentOffset = (0, 30.0)

switch contentOffset {
  case let (_, y) where y < 0: print("Scrolled up")
  case let (_, y) where (0...60) ~= y: print("scrolling top area")
  default: println("just scrolling")
}
```

## Swift 2

**New in Swift 2**, you can now use any Swift pattern as the clause of an if statement:

``` swift
let comments = 7

if case 1...10 = commentCount {
    print("some comments")
} else if case 11..100 = commentCount {
    print("lots of comments")
}
```

And in **Swift 2**'s new error handling:

``` swift
do {
    try send(message: "Hello")
} catch SendError.Offline {
    print("user is offline")
} catch SendError.RateLimited {
    print("stop spamming")
} catch SendError.Blocked(let reason) {
    print("user was blocked because \(reason)")
}
```
