Skip to content
Justice Tech School

compactMap and flatMap

compactMap drops nils and flatMap flattens nested arrays.

Example
let s = ["1", "x", "3"]
print(s.compactMap { Int($0) })
print([[1], [2, 3]].flatMap { $0 })
print([1, 2, 3].enumerated().map { $0.offset * $0.element })

Exercise

Drop nils.

s. { Int($0) }

Quiz Test

What does compactMap remove?

These free lessons are for learning. Join a full course for projects, mentor feedback and a verified certificate.