Swift Set isEmpty

The isEmpty property checks if the set is empty or not.

Example

var languages: Set = ["Swift", "C", "Java"]

// check if languages is empty or not var result = languages.isEmpty
print(result) // Output: false

isEmpty Syntax

The syntax of the set isEmpty property is:

set.isEmpty 

Here, set is an object of the Set class.


isEmpty Return Values

The isEmpty property returns:

  • true - if the set does not contain any elements
  • false - if the set contains some elements

Example 1: Swift set isEmpty

var names: Set = ["Alcaraz", "Sinner", "Nadal"]

// check if names is empty or not print(names.isEmpty)
var employees = [String]()
// check if employees is empty or not print(employees.isEmpty)

Output

false
true

In the above example, since

  • names contain three string elements, the property returns false.
  • employees is an empty set, the property returns true.

Example 2: Using isEmpty With if...else

var names: Set = ["Federer", "Thiem"]

// false because names contains three elements if (names.isEmpty) {
print( "Set is empty") } else { print("Elements:", names) }

Output

Elements: ["Federer", "Thiem"]

Here, the names set is not empty, so the if block is skipped and the else block is executed.

Did you find this article helpful?

Our premium learning platform, created with over a decade of experience and thousands of feedbacks.

Learn and improve your coding skills like never before.

Try Programiz PRO
  • Interactive Courses
  • Certificates
  • AI Help
  • 2000+ Challenges