Swift Program to Remove Null from a Set


In swift, a set is used to create an unordered collection of unique elements. In Swift, to store a nil value in the set you need to define the set as a optional type because nil is a optional value. So to remove null for a set we can use inbuilt functions like remove() and filter(). Lets discuss both the methods in detail along with examples.

Method 1: Using remove(_:) Function

The remove(_:) function is used to remove or delete a specified element from the given set.

Syntax

func remove(ele)

Where ele is the element which we want to remove from the specified set. This function return a value of the eye parameter if it was a part of the given set. Otherwise return nil.

Example

In the following code, we will first create an optional set to store a nil value in it. Then using remove(_:) function we removed nil value and then display the updated set.

import Foundation
import Glibc

// Creating optional type set to store nil value 
var mySet: Set<Int?> = [23, nil, 21, nil, 98, nil]

// Removing null from optional set
mySet.remove(nil)

print("Set:", mySet)

Output

Set: [Optional(21), Optional(98), Optional(23)]

Method 2: Using filter(_:) Function

Swift provide an inbuilt function named as filter(_:). This function is used to return a collection which contains only those elements that satisfy the given criteria.

Syntax

func filter{col}

Where col is closure which takes an element form the given sequence and return boolean value which indicates whether the given element should include in the return collection.

Example

In the following swift example, we will first create an optional set to store null as well as string values in it. Then use filter() function to create a new set that contains only non-null values, here we use {$0 != nil} closure to remove nil values. Then using the map() function we convert the optional set into the non-optional set because we already filter out the nil values, so not we can safely use the forced unwrapping operator(‘!’) To convert optional values into non-optional values. And display the result

import Foundation
import Glibc

// Creating optional type set to store nil value 
var mSet: Set<String?> = ["mox", "fox", nil, "kox", nil, "aox"]

// Filter out null values
let newSet = mSet.filter { $0 != nil }.map { $0! }

print("New Set with no null values:", newSet)

Output

New Set with no null values: ["kox", "fox", "aox", "mox"]

Conclusion

So this is how we can remove null from a set. Here, don’t get confused if the order of set elements change because set is an unordered collection. Also you can not store nil in non-optional set, if you try to do you will get error.

Updated on: 24-Apr-2023

217 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements