Swift Set count

The count property returns the total number of elements present in the set.

Example

var employees: Set = ["Ranjy", "Sabby", "Pally"]

// count total number of elements in languages var result = employees.count
print(result) // Output: 3

count Syntax

The syntax of the set count property is:

set.count 

Here, set is an object of the Set class.


count Return Values

The count property returns the total number of elements present in the set.


Example 1: Swift Set count

var names: Set = ["Gregory", "Johnny", "Kate"]

// count total elements on names print(names.count)
var employees = Set<String>()
// count total elements on employees print(employees.count)

Output

3
0

In the above example, since

  • names contain three string elements, the property returns 3.
  • employees is an empty set, the property returns 0.

Example 2: Using count With if...else

var numbers: Set = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

// true because there are 10 elements on numbers if (numbers.count > 5) {
print( "The set size is large") } else { print("The set size is small") }

Output

The set size is large

In the above example, we have created the set named numbers with 10 elements.

Here, since there are 10 elements in the set, numbers.count > 5 evaluates to true, so the statement inside the if block is executed.