How to remove nil elements from an array in Swift

⋅ 1 min read ⋅ Swift Array

Table of Contents

If you have an array with optional values, you can easily filter out nil elements from that array using the compactMap(_:) method.

In the following example, we have an optional string array, optionalColors. You can filter nil value out of any array by calling compactMap(_:) on that array.

let optionalNumbers: [String?] = ["1", "2", nil, "3", "four"]
let nonOptionalNumbers: [String] = optionalNumbers.compactMap { $0 }
// ["1", "2", "3", "four"]

A compact map is a map function but more compact (no nil value). You can make any transform with each element in the passing closure, and compactMap will make sure there is no nil value in the resulting array.

Here is another example where we try to parse a number String into an Int.

let optionalNumbers = ["1", "2", nil, "3", "four"]       
let nonOptionalNumbers = optionalNumbers.compactMap { numberString in
if let numberString {
// 1
return Int(numberString)
} else {
return nil
// [1, 2, 3]

1 Parsing a string into an integer is a failable constructor, init?(_ description: String), but compactMap will ensure the resulting array contains only non-nil values.

Read more article about Swift, Array, or see all available topic

Enjoy the read?

If you enjoy this article, you can subscribe to the weekly newsletter.
Every Friday, you'll get a quick recap of all articles and tips posted on this site. No strings attached. Unsubscribe anytime.

Feel free to follow me on Twitter and ask your questions related to this post. Thanks for reading and see you next time.

If you enjoy my writing, please check out my Patreon and become my supporter. Sharing the article is also greatly appreciated.

Become a patron Buy me a coffee Tweet Share
How to change TabView color in SwiftUI

In iOS 16, SwiftUI got a way to change the bottom tab bar background color with the new modifier, toolbarBackground.

How to adjust List row separator insets in SwiftUI

In iOS 16, we can adjust a List row separator insets with the new alignment, listRowSeparatorLeading.

← Home