Swift Program to Check if a Set is empty


In Swift, a set is used to create a collection of unique elements. In a set, the elements are not arranged in a particular order. Now to check if a set is empty or not Swift provide an inbuilt property named as isEmpty. This property will return true if the given set is empty. Otherwise it will return false.

Syntax

newSet.isEmpty

Where newSet is the name of the set and we can access the isEmpty property using the dot operator. This property's return type is bool, meaning if it returns true, it means the set is empty. If it return false means the set if not empty.

Example 1

In the this example, we create three different type of sets. Now using isEmpty property we check if they are empty of not. If we get true, which means the set is empty. Otherwise, the specified set is not empty.

import Foundation
import Glibc

// Creating sets
var myFavNum: Set<Int> = [12, 98, 34, 1, 34, 22, 67]
var myColor: Set<String> = []
var mySet = Set<Double>()
var myNum: Set = [45.4, 32.1, 2.3, 5.6, 32.2, 44.3]

// checking if the set is empty or not
print("Is myFavNum set is empty?:", myFavNum.isEmpty)
print("Is myColor set is empty?:", myColor.isEmpty)
print("Is mySet set is empty?:", mySet.isEmpty)
print("Is myNum set is empty?:", myNum.isEmpty)

Output

Is myFavNum set is empty?: false
Is myColor set is empty?: true
Is mySet set is empty?: true
Is myNum set is empty?: false

Example 2

In the following example, we create two sets. Now we use the if else statement with condition (myFavNum.isEmpty == true) to check whether the given set is empty. If the set is empty print ”The given set is empty”. Otherwise, print “The set is not empty”.

import Foundation
import Glibc

// Creating sets
var myFavNum: Set = [22, 43, 33, 56, 34, 88, 16]
var myColor: Set<String> = []

// Checking if the set is empty or not
if (myFavNum.isEmpty == true){
   print("The given set is empty")
}
else{
   print("The set is not empty")
}

// Checking if the set is empty or not
if (myColor.isEmpty == true){
   print("The given set is empty")
}
else{
   print("The set is not empty")
}

Output

The set is not empty
The given set is empty

Conclusion

So this is how we can check if a set is empty or not. Here the isEmpty property return result into bool so their is not need to unwrap an optional value.

Updated on: 06-Apr-2023

259 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements