Menu
Coddy logo textTech

compactMap

Part of the Logic & Flow section of Coddy's Swift journey — lesson 28 of 56.

compactMap is map with the optionals filtered out. The closure can return an Optional; compactMap drops the nil results and unwraps the rest.

let strings = ["3", "hi", "7", "!", "1"]
let numbers = strings.compactMap { Int($0) }
print(numbers)               // [3, 7, 1]

Int("hi") returns nil because it can't parse a number from "hi". compactMap throws those out automatically and gives you a clean [Int].

Without it, you'd write strings.map { Int($0) } and get an [Int?] with nils mixed in, then have to filter them out yourself. compactMap does both steps in one.

challenge icon

Challenge

Easy

Read a single line of input: a comma-separated mix of integers and garbage text (some entries can't be parsed).

Print:

  1. The integers (in input order), joined with ,
  2. How many entries were dropped (couldn't be parsed)
  3. The sum of the parsed integers

For input 3,hi,7,!,1,42,oops, the output is:

3,7,1,42
3
53

Cheat sheet

compactMap works like map but automatically removes nil results and unwraps the rest:

let strings = ["3", "hi", "7", "!", "1"]
let numbers = strings.compactMap { Int($0) }
// [3, 7, 1]  — nils from unparseable strings are dropped

Without compactMap, map would return [Int?] with nils mixed in, requiring a separate filter step.

Try it yourself

let parts = readLine()!.components(separatedBy: ",")

// TODO: compactMap to ints; print joined, dropped count, sum
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Logic & Flow