How to remove nil elements from an array in Swift?

Uplift iOS Interview

The Guide is for YOU if
  • You are preparing for an iOS interview and want to improve your skills and knowledge and looking to level up your interview game and land your dream job.
  • You want to gain confidence and ease during iOS interviews by learning expert tips and curated strategies.
  • You want access to a comprehensive list of iOS interview QA to practice and prepare.

In this blog post, we’re going to explore how to remove nil elements from an array in Swift. An array is a very useful data structure, but sometimes it can contain elements that have the value of nil. This can lead to unexpected behavior in our code, and it’s important to remove those nil values before using the array. In this post, we’ll cover some of the ways you can remove nil elements from an array in Swift.

The first and most common way to remove nil elements from an array is by using the filter function. This function takes a closure as a parameter, and the closure is used to determine which elements should be kept in the array. Here’s an example of how to use filter to remove nil elements from an array:

let array = [1, 2, nil, 3, nil, 4]
let filteredArray = array.filter { $0 != nil }
print(filteredArray) // [1, 2, 3, 4]

In this example, the closure { $0 != nil } is used to filter out any elements that are equal to nil. The filter function then returns a new array that contains only the non-nil elements.

Another way to remove nil elements from an array is by using the compactMap function. This function works similarly to filter, but it also allows you to transform the non-nil elements while they’re being filtered. Here’s an example of how to use compactMap to remove nil elements from an array and also map the remaining elements:

let array = ["1", "2", nil, "3", nil, "4"]
let filteredArray = array.compactMap { Int($0) }
print(filteredArray) // [1, 2, 3, 4]

In this example, compactMap calls the closure { Int($0) } for each element in the array, if the element is not nil the closure return a new non-nil value otherwise compactMap will remove the element from the array.

You also can remove nil elements using for-in loop:

var array = ["1", "2", nil, "3", nil, "4"]
for (index, value) in array.enumerated().reversed() {
    if value == nil {
        array.remove(at: index)
    }
}
print(array) // ["1", "2", "3", "4"]

The above code uses the enumerated() function to loop through the array and check each element, if the element is equal to nil, it is removed from the array using the remove(at:) function. Keep in mind this approach works only with mutable arrays and will have performance implications for large arrays.

In conclusion, there are several ways to remove nil elements from an array in Swift. The filter function and the compactMap function are the most common, but you also can use for-in loop. Each approach has its own advantages and limitations, so it’s important to choose the one that fits best with your specific use case. Always consider the performance and the best approach that suits your needs.



✍️ Written by Ishtiak Ahmed

👉 Follow me on XLinkedIn



Get Ready to Shine: Mastering the iOS Interview




Enjoying the articles? Get the inside scoop by subscribing to my newsletter.

Get access to exclusive iOS development tips, tricks, and insights when you subscribe to my newsletter. You'll also receive links to new articles, app development ideas, and an interview preparation mini book.

If you know someone who would benefit from reading this article, please share it with them.