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
EasyRead a single line of input: a comma-separated mix of integers and garbage text (some entries can't be parsed).
Print:
- The integers (in input order), joined with
, - How many entries were dropped (couldn't be parsed)
- The sum of the parsed integers
For input 3,hi,7,!,1,42,oops, the output is:
3,7,1,42
3
53Cheat 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 droppedWithout 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
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Logic & Flow
1Strings In Depth
Count and IndicesCase and TrimSearching in StringsSplitting and JoiningReplacing SubstringsRecap - Username Check