Swift Set isEmpty

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


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:


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)



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) }


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?