0
0
Swiftprogramming~3 mins

Why CompactMap for optional unwrapping in Swift? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

What if you could skip all the messy checks and get only the good data with one simple command?

The Scenario

Imagine you have a list of phone numbers, but some are missing or invalid. You want to get only the valid numbers to call. Doing this by hand means checking each number one by one and skipping the empty or wrong ones.

The Problem

Manually checking each item is slow and easy to mess up. You might forget to skip a missing number or accidentally include a wrong one. This makes your code long, confusing, and full of mistakes.

The Solution

Using compactMap lets you quickly filter out all the missing or invalid values in one simple step. It unwraps optionals and removes nils automatically, making your code clean and safe.

Before vs After
Before
var validNumbers = [String]()
for number in numbers {
  if let valid = number {
    validNumbers.append(valid)
  }
}
After
let validNumbers = numbers.compactMap { $0 }
What It Enables

It lets you easily work only with real, usable data without clutter or errors from missing values.

Real Life Example

When loading user input where some fields might be empty, compactMap helps you get only the filled-in answers to process further.

Key Takeaways

Manually unwrapping optionals is slow and error-prone.

compactMap unwraps and filters nils in one step.

This makes your code cleaner, safer, and easier to read.