Swift: Counting the Number of Elements in a Set

Updated: May 9, 2023 By: Khue Post a comment

In Swift, you can count the number of elements in a set by using the count property.

Example:

let words = Set(["Sling", "Academy", "Swift", "iOS"])
let count = words.count
print("The set contains \(count) elements.")

Output:

The set contains 4 elements.

An empty set is a set that contains no elements. You can check whether a set is empty or not like so:

var numbers = Set<Int>()
if(numbers.count == 0){
    print("Empty")
} else {
    print("Not Empty")
}

Output:

Empty

A better solution to check if a set is empty is to use the isEmpty property as shown below:

var numbers = Set<Int>()
if(numbers.isEmpty){
    print("Empty")
} else {
    print("Not Empty")
}

This concise tutorial ends here. Happy coding & have a nice day!