0
0
Swiftprogramming~5 mins

CompactMap for optional unwrapping in Swift

Choose your learning style9 modes available
Introduction

CompactMap helps you clean up a list by removing empty or missing values. It unwraps optionals safely and keeps only real values.

You have a list with some missing or empty values and want only the real ones.
You want to convert a list of strings to numbers, ignoring the ones that can't be converted.
You want to filter out nil values from a list of optional items.
You want to clean user input data by removing blanks or invalid entries.
Syntax
Swift
let newArray = oldArray.compactMap { item in
    // return a non-optional value or nil
}

The closure inside compactMap must return an optional value.

compactMap removes all nil results and unwraps the rest.

Examples
This converts strings to integers, ignoring "three" which can't be converted.
Swift
let strings = ["1", "2", "three", "4"]
let numbers = strings.compactMap { Int($0) }
print(numbers)
This removes nil values from a list of optional integers.
Swift
let optionalInts: [Int?] = [1, nil, 3, nil, 5]
let ints = optionalInts.compactMap { $0 }
print(ints)
Sample Program

This program takes a list of strings, tries to convert each to an integer, and keeps only the valid numbers.

Swift
let mixedStrings = ["10", "abc", "20", "", "30"]

let validNumbers = mixedStrings.compactMap { str in
    Int(str)
}

print("Valid numbers:", validNumbers)
OutputSuccess
Important Notes

compactMap is great for safely unwrapping optionals while filtering out nils.

It is different from map because map keeps nils as optionals, compactMap removes them.

Summary

compactMap unwraps optionals and removes nil values from collections.

Use it to clean lists by keeping only real, non-nil values.

It helps avoid crashes from forced unwrapping of nil optionals.