Swift Program to remove all 'nil' elements from the array


In this article, we will learn how to write a swift program to remove all ‘nil’ elements from the array.

Till now we all know that an array can store elements of a single data type. But Swift array can also hold elements of multiple data types. To store multiple data types in the array we use [Any], where [Any] specifies that the address can hold elements of any data types. Similarly an array also contain nil value. Here we use the following methods to remove nil elements from the array.

  • Using compactMap() function

  • Using filter() function

Method 1: Using compactMap() Function

To remove all `nil` elements from the array we use compactMap() function. The compactMap() function takes a sequence as an input which contain nil elements and transforms the result into an array which contain only non-nil elements.

Syntax

func compactMap<elementOfResult>(_tClosure:(self.Element)throws -> elementOfResult?)rethrows -> [elementOfResult]

Here, tClosure is a closure which takes items from the given sequence as an argument and return an optional value.

Algorithm

  • Step 1 − Create an array with nil values.

  • Step 2 − Print the original array.

  • Step 3 − Remove nil elements from the array using compactMap() function.

  • Step 4 − Print the modified array.

Example

Following Swift program to remove all ‘nil’ elements from the array.

import Foundation
import Glibc

// Creating an array with nil value 
let mArray: [String?] = ["cloud", "sky", nil, "moon", nil, "bird", nil]

print("Original Array:", mArray)

// Removing nil values
let noNilArray: [String] = mArray.compactMap { $0 }

print("Modified Array:", noNilArray)

Output

Original Array: [Optional("cloud"), Optional("sky"), nil, Optional("moon"), nil, Optional("bird"), nil]
Modified Array: ["cloud", "sky", "moon", "bird"]

Here in the above code, we have an array of string type. Now using compactMap() function we iterate through each element of the given array starting from index 0 and remove the nil element from the array. Hence the resultant array contain only non-nil elements.

Method 2: Using filter(_:) function

We can also use filter() function to remove nil elements from the array. The filter(_:) function returns an array, which contains all the elements that satisfy the given condition.

Syntax

func filter(_mClosure:(self.Element) throws -> Bool)rethrows->[Self.Element]

Here, mClosure is a closure which which takes items from the given sequence as an argument and return a boolean value indicating whether the element should be included in the returned array or not.

Algorithm

  • Step 1 − Create an array of integer type.

  • Step 2 − Print the original array.

  • Step 3 − Remove nil elements from the array using filter() function

  • Step 4 − Print the output.

Example

Following Swift program to remove all ‘nil’ elements from the array.

import Foundation
import Glibc

// Creating an array of integer types
var mArray = [23, nil, 4, 3, nil, 21, 12, nil, nil]

print("Original array:", mArray)

// Removing nil elements
var res = mArray.filter { $0 != nil }

print("Modified array:", res)

Output

Original array: [Optional(23), nil, Optional(4), Optional(3), nil, Optional(21), Optional(12), nil, nil]
Modified array: [Optional(23), Optional(4), Optional(3), Optional(21), Optional(12)]

Here in the above code, we have an array of integer type. Now we use filter() function to remove will elements from the given array. So for that we pass { $0 != nil } as a closure in the filter() function. This closure takes elements from the given array starting from index 0 to end and check each element is not equal to nil. If the condition is true, then it adds that element in the resultant array. Otherwise it remove that nil element.

Conclusion

So this is how we can remove all ‘nil’ elements from the array. Here both the methods return accurate result and they work for any data types.

Updated on: 17-Jan-2023

561 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements