map and compactMap
Transform elements and drop nils.
map and compactMap is a free Swift Academy lesson on CoddyKit. This is lesson 1 of 4. Any 3 lessons of this learning path are free to read in full — after that, CoddyKit PRO unlocks every lesson, plus hands-on practice with a built-in code editor and a 24/7 AI tutor. It is part of the Swift Academy learning path, and your progress syncs across the web and the CoddyKit app. The Swift Academy course includes 4 lessons in total.
What Is map?
map is a higher-order function: it takes a closure and applies it to every element of a sequence, returning a new array of the transformed results.
- The original collection is never mutated
- The result count always equals the input count
- The element type can change (e.g.
Int→String)
A Simple map
Doubling every number in an array:
let numbers = [1, 2, 3, 4]
let doubled = numbers.map { $0 * 2 }
print(doubled) // [2, 4, 6, 8]Changing the Element Type
map can transform Int values into String values:
let ids = [10, 20, 30]
let labels = ids.map { "ID-\($0)" }
print(labels) // ["ID-10", "ID-20", "ID-30"]map with a Named Function
You can pass any function with a matching signature, not just a trailing closure:
let words = ["swift", "map"]
let upper = words.map { $0.uppercased() }
print(upper) // ["SWIFT", "MAP"]The Problem map Cannot Solve
map keeps every element. If your transform returns an optional (it might fail), you end up with an array of optionals like [Int?] — full of nil holes you must filter later.
That is exactly what compactMap solves.
Enter compactMap
compactMap transforms each element and drops any result that is nil, returning a non-optional array:
let raw = ["1", "2", "x", "4"]
let nums = raw.compactMap { Int($0) }
print(nums) // [1, 2, 4] -- "x" was droppedmap vs compactMap Side by Side
The difference is whether nil results survive:
let raw = ["1", "x", "3"]
print(raw.map { Int($0) }) // [Optional(1), nil, Optional(3)]
print(raw.compactMap { Int($0) }) // [1, 3]Unwrapping Optionals in a Collection
compactMap is the idiomatic way to strip nils out of an array of optionals:
let maybe: [Int?] = [1, nil, 3, nil, 5]
let clean = maybe.compactMap { $0 }
print(clean) // [1, 3, 5]Parsing with compactMap
A common real use: parse only the valid lines of input:
let lines = ["42", "", "hello", "7"]
let values = lines.compactMap { Int($0) }
print(values) // [42, 7]
print(values.reduce(0, +)) // 49Combining map and compactMap
You can chain them: map to shape data, compactMap to keep only the successes:
let scores = ["90", "85", "n/a", "70"]
let passed = scores
.compactMap { Int($0) }
.map { $0 >= 80 ? "pass" : "fail" }
print(passed) // ["pass", "pass", "fail"]compactMap on Optional Chains
It also works beautifully with optional property access:
struct User { let name: String? }
let users = [User(name: "Ann"), User(name: nil), User(name: "Bo")]
let names = users.compactMap { $0.name }
print(names) // ["Ann", "Bo"]Quick Check
Which function transforms elements and removes nil results in one step?
Recap
You learned the two core transforming functions:
map— transform every element, result count equals input countcompactMap— transform and dropnil, great for parsing and unwrapping optionals- Both return new arrays and never mutate the source
- Chain them to shape then filter data cleanly
Next: filtering with predicates.
Learn Swift with an AI tutor — free
Write and run real code in your browser, get instant help from a 24/7 AI tutor, and pick up where you left off on the web or in the app.
- Courses
- 122
- Lessons
- 409
Frequently Asked Questions
Is the “map and compactMap” lesson free?
Yes — any 3 lessons of the Swift Academy learning path, including “map and compactMap”, are free to read in full here on the web. After that, CoddyKit PRO unlocks every lesson, plus interactive practice with a built-in code editor and a 24/7 AI tutor. The Swift Academy course includes 4 lessons in total.
What will I learn in “map and compactMap”?
Transform elements and drop nils. You practise Swift Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start Swift Academy?
No prior experience is required. Swift Academy on CoddyKit is structured for beginners through advanced learners, so you can start here or from the beginning and move at your own pace. This is lesson 1 of 4.
How long does the “map and compactMap” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this Swift Academy lesson?
Yes. Every Swift Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- map and compactMap
- filter and Predicates
- reduce and reduce(into:)
- flatMap and Chaining