0Pricing
Swift Academy · Lesson

map and compactMap

Transform elements and drop nils.

map and compactMap is a free Swift Academy lesson on CoddyKit — lesson 1 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Swift Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

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. IntString)

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 dropped

map 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, +))  // 49

Combining 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 count
  • compactMap — transform and drop nil, 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.

Frequently asked questions

Is the “map and compactMap” lesson free?

Yes — the full text of “map and compactMap” is free to read here on the web, and the Swift Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Swift Academy course, upgrade to CoddyKit PRO.

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; this is — lesson 1 of 4, so you can start here or from the beginning and move at your own pace.

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

  1. map and compactMap
  2. filter and Predicates
  3. reduce and reduce(into:)
  4. flatMap and Chaining
← Back to Swift Academy