Swift – Count Number of Values in a Set

To get a count of the number of elements or size of a Set, use Set.count property.

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

Syntax

The syntax to access count property of the Set set is

set.count
ADVERTISEMENT

Examples

In the following example, we initialize a Set of integers, and find the size of this Set using count property.

main.swift

var numbers: Set = [25,12,74,16,18]
var size = numbers.count
print("Size of Set is: \(size)")

Output

Size of Set is: 5

In the following example, we initialize a Set of Strings containing names of students, and we find the size of this Set using count property.

main.swift

var names: Set = ["John", "Rafel", "Sindhu"]
var size = names.count
print("Size of Set is: \(size)")

Output

Size of Set is: 3

Conclusion

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