Understanding Map on Optionals.

abdul ahad
2 min readMay 25, 2024
Photo by Fauzan Saari on Unsplash

The map function on an optional allows you to apply a transformation (a function) to the wrapped value if it is non-nil, and returns a new optional containing the result of the transformation. If the optional is nil, map simply returns nil.

Code Explanation

// function
func didComplete(with credentials: Credentials) {
//...
}

//calling site
let appleIDCredential = authorization.credential as? Credentials
appleIDCredential.map(didComplete)

Here’s what happens step-by-step:

  1. Optional Casting: let appleIDCredential = authorization.credential as? Credentials
  • This line attempts to cast authorization.credential to Credentials. If the cast is successful, appleIDCredential will be an optional containing the Credentials value. If the cast fails, appleIDCredential will be nil.
  1. Optional Mapping: appleIDCredential.map(didComplete)
  • This line applies the map function to appleIDCredential.
  • If appleIDCredential is nil, map does nothing, and the result is nil.
  • If appleIDCredential is non-nil, map calls the didComplete function with the unwrapped appleIDCredential value.

Detailed Behavior of map in this Case

  • If appleIDCredential is nil:
appleIDCredential.map(didComplete) // Does nothing, result is nil
  • If appleIDCredential contains a value (let's say of type Credentials):
appleIDCredential.map(didComplete)
// Internally calls didComplete(with: appleIDCredential)

Why Use Map Here?

Using map is a concise and idiomatic way to handle the optional Credentials value. It ensures that the didComplete(with:) function is called only if appleIDCredential is non-nil, eliminating the need for an explicit if let or guard statement.

The equivalent code using an explicit if let statement would be:

if let appleIDCredential = appleIDCredential {
didComplete(with: appleIDCredential)
}

guard let appleIDCredential = appleIDCredential else{return}
didComplete(with: appleIDCredential)

Using map simplifies this pattern:

appleIDCredential.map(didComplete)

Summary

The map function in this context provides a succinct way to call didComplete(with:) only if appleIDCredential is non-nil. It effectively unwraps the optional and applies the function to its value, making your code cleaner and more readable.

--

--

abdul ahad
abdul ahad

Written by abdul ahad

A software developer dreaming to reach the top and also passionate about sports and language learning

No responses yet