SWIFTBITES Issue NO. 1 — Optional Pattern Matching

Sebastian Boldt
iOS App Development
3 min readOct 16, 2016

Hey Followers, this is the first issue of Swift Bites. These series will focus on Swift features and problem-solving techniques using Swift. I will examine everything interesting I discover during my daily work as an iOS Developer. I will try to keep these posts a lot shorter than my regular Articles so that I can release them more frequently.

An Optional Feature I didn't know so far

Lately, I was working on the Swift 3.0 Port of our App. So at first I triggered the automatic Swift conversion. A lot of stuff was altered automatically by the converter. Rewriting enums to lowercase, refactoring dispatch_once calls and a lot of other things.

One thing that instantly caught my attention was the code added by the converter to remove the implicit comparison of optionals in Swift 2.0. What I mean by that is the possibility to compare optionals without actually unwrapping them. Swift 3.0 does not support that anymore. So what the Converter does is that he adds two generic compare functions to solve that issue.

fileprivate func < <T : Comparable>(lhs: T?, rhs: T?) -> Bool {  switch (lhs, rhs) {    case let (l?, r?):      return l < r    case (nil, _?):      return true    default:      return false  }}fileprivate func > <T : Comparable>(lhs: T?, rhs: T?) -> Bool {  switch (lhs, rhs) {    case let (l?, r?):      return l > r    default:      return rhs < lhs  }}

There is a special syntax used in that functions that I have never seen before.

case let (l?, r?): // Line 3

Thanks to Google I quickly found out that it is called the Optional Matching Pattern (Not sure if this is the official name for it). Because an Optional is just an enum (Read more about that: Swift! Optionals?) you can use the switch case syntax like on a regular enumeration.

let x: String? = “Hello Optional”switch x {  case .some(let value): print(“Optional has an value of \(value)”)  case .none: print(“nothing stored inside the enum”)}

If you want to check if two optionals have a value with the help of a switch-case statement, you will most likely try to do something similar to this code:

let x: String? = nillet y: String? = "Hello Optional"switch (x,y) {  case (.some(let a),.some(let b)): print("Values \(a) & \(b)")  default: print(“Error”)}

This will work but there are too many brackets for my taste. Thank God, Swift comes with a great shorthand syntax I didn't know so far. You have already seen this above.

let x: String? = “Hello Optional”let y: String? = “Hello Optional”switch (x,y) {  case let (a?,b?): print(“Values: \(a) & \(b)”)  default: print(“Error”)}

So the question-mark after a variable definition inside a case condition just means: “If there is a value inside the switched optional put it into the variable”. Great right?

That’s it. I hope you enjoyed the first issue of Swift Bites. Feel free to add me on github, twitter, linkedin or xing if you have any questions. If you like electronic music you can also listen to my Tracks on SoundCloud ;)

Ciao!

Sebastian Boldt

--

--

Sebastian Boldt
iOS App Development

Creative Head, iOS Developer @ Immowelt, DJ/Producer from Hamburg. Creator of HabitBe, a weekly Habit Tracker written in SwiftUI. https://www.sebastianboldt.com