Unwrapping Optionals the quick way in Swift

A strange yet quick way to unwrap optionals and operate on them.

Pavan Kataria
2 min readJun 12, 2020

How do you optionally (pun intended) operate on an optional if a value is present? Today we explore how.

Shows a user-input interface containing a number keypad with cells in a tableview displaying number values

Above is a screen for an application which takes in optional string inputs and stores them in the form of an optional number in the cell model. The method for processing a String? into an Int? may look something like this using the if let syntax:

It looks messy, and we can do better. A quicker way of doing this is to use the flatMap method.

flatMap

This term usually floats around in the topic of Higher-Order Functions — the method which simply-put transforms sub-collections into a single collection. But we’re not referring to this method today. Many may not know about a flatMap method which can be worked with on Optionals.

Here’s what the same example above looks like using flatMap on the optional stringNumber

For syntactic sugar you can pass in the Int initialiser directly like so too: stringNumber.flatMap(Int.init)

How does Optional’s flatMap work?

This is what the signature of flatMap looks like in the Optional enum.

public func flatMap<U>(_ transform: (Wrapped) throws -> U?) rethrows -> U?

What flatMap does to an Optional is if the value exists it will unwrap the optional and allow you transform on it. If the optional instance is nil then it will return nil. The method would look something like this:

What flatMap does to an Optional is if the value exists it will unwrap the optional and allow you to transform on it. If the optional instance is nil then it will return nil.

Chain away

You can also use this method in-line and even chain for more expressive code. This is incredibly useful when you have to use multiple varying operations that all can return nil. Here’s a somewhat contrived example:

Understanding how to use flatMap can save you time, reduce verbosity, and will allow your code to be more expressive.

I really hope you liked the article. If you want to support my work then check out my other articles and feel free to share them with colleagues and friends. You can also find me on Github where I maintain a couple of open source packages.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

Pavan Kataria
Pavan Kataria

Written by Pavan Kataria

Engineer Pavan, First of His name, the Unburnt, Lord of the iOS Realm, Bug Breaker, Space Indenter, and New writer — otherwise known as PK

No responses yet

Write a response