Remove nil elements from an array while changing the array type
1 min read

Remove nil elements from an array while changing the array type

I always forget how to remove nil elements from an array in a functional way in Swift.

Here it is:

let arrayWthOptionals: [String?] = ...
let arrayWithoutOptionals: [String] = arrayWthOptionals.compactMap ({ $0 })

The resulting array is an array of non-optional.

Subscribe to a curated newsletter

Receive an email every week with curated content about Dart and Flutter.

See previous issues of the newsletter.