Open In App

How to check if a set is empty in Swift?

Last Updated : 02 Jun, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

Swift supports the different types of generic collections and set is one of them. A set is used to store unordered values of the same type. It means you are not allowed to keep different types in the set. You can use a set instead of an array if the order of the values is not defined or you want to store unique values. It doesn’t keep duplicate values, it always keeps unique values in it. It generally uses a hash table to store the elements. We can also check if the given set is empty or not with the help of the isEmpty property. This property returns true if the given set is empty or returns false if the given set contains some elements. 

Syntax:

setName.isEmpty

Here, 

setName is the object of the set class.

Return Value: This property will return true if the given set is empty or return false if the given set contains elements.

Example 1:

Swift




// Swift program to check if the given set is empty or not
import Swift
  
// Creating an set of EmployeeSalary
// Here the set is of int type
var GEmpSalary: Set = [30000, 12200, 14000, 67800, 10000, 90000]
  
// Checking the given set is empty or not
// Using isEmpty property
var result1 = GEmpSalary.isEmpty
  
// Displaying the result
print("Is the GEmpSalary is empty or not?", result1)
  
// Creating an empty set of int type
var GEmployee = [Int]()
  
// Finding the total number
var result2 = GEmployee.isEmpty
  
// Displaying the result
print("Is the GEmployee is empty or not?", result2)


Output:

Is the GEmpSalary is empty or not? false
Is the GEmployee is empty or not? true

Example 2:

Swift




// Swift program to check if the given set is empty or not
import Swift
  
// Creating an set of Authors Name
// Here the set is of string type
var GName: Set = ["Minaxi", "Prita", "Mona", "Guri", "Om", "Rohit"]
  
// Checking the given set is empty or not
// Using isEmpty property
if (GName.isEmpty == true)
{
    print("Yes! the given Set is empty")
}
else
{
    print("No! the given Set is not empty")
}


Output:

No! the given Set is not empty


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads