Topics

#22: Pattern Matching 🔠🔢

Topics

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

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

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

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

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:

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:

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)")
}