Swift – Count Number of elements in a Set

In this tutorial, we will learn how to get the size of a set or count the number of elements in a Swift Set.

To get a count of the number of elements or size of a Set, use Set.count method. Following is the syntax.

setName.count

Example 1: Get the size of Set using the count function

In this example, we initialize a Set of numbers, and we will find the size of the Set.

var numbers: Set = [25,12,74,16,18]

var size = numbers.count

print("Size of Set is: \(size)")
Size of Set is: 5

Example 2: Get the size of Set containing Strings using the count function

In this example, we initialize a Set of Strings containing names of students, and we will find the size of the Set.

var names: Set = ["John", "Rafel", "Sindhu"]

var size = names.count

print("Size of Set is: \(size)")
Size of Set is: 3

Conclusion

In this Swift Tutorial, we have learned to get the size of a Set using count function with the help of Swift example programs.