Swift Set - Counting and Checking Elements

Here we will explain how to get the number of elements in a Swift Set, how to check if a Set is empty, and how to check if a Set contains a specific element.

Using the count Property to Get the Number of Elements in a Set

If you want to get the number of elements in a Swift Set, use the count property of the Set.

let numbers: Set = [1, 2, 3, 4, 5]
print(numbers.count)

The output will be as follows. Since there are 5 elements, it prints 5.

5

Using the isEmpty Property to Check if a Set is Empty

To check if a Set in Swift is empty, you can use the isEmpty property.

var numbers: Set = [1, 2, 3, 4, 5]
print(numbers.isEmpty)

numbers.removeAll()
print(numbers.isEmpty)

The output is as follows. After using the removeAll() method, the Set becomes empty and numbers.isEmpty returns true.

false
true

Using contains() to Check if a Set Contains a Specific Element

To check if a Swift Set contains a specific element, you can use the contains() method.

For example, to check if the numbers Set contains 3 and 6, you can do the following:

let numbers: Set = [1, 2, 3, 4, 5]

print(numbers.contains(3))
print(numbers.contains(6))

The output will be as follows. Since 3 exists, it returns true. Since 6 does not exist, it returns false.

true
false

That wraps up how to get the number of elements in a Swift Set, check if a Set is empty, and check if a Set contains a specific element.