Swift Set capacity

The capacity property returns the number of elements of the set without allocating any additional storage.

Example

var languages: Set = ["Swift", "C", "Java"]

// check if leanguages is empty or not var result = languages.capacity
print(result) // Output: 3

capacity Syntax

The syntax of the set capacity property is:

set.capacity 

Here, set is an object of the Set class.


capacity Return Values

The capacity property returns the total number of elements present in the set without allocating any additional storage.


Example 1: Swift set capacity

var names: Set = ["Gregory", "Perry", "Nadal"]

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

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.

The capacity property here returns a total number of elements of names and employees without allocating new storage.


Example 2: Using capacity With if...else

var numbers: Set = [1, 2, 3]

// true because there are only 3 elements on numbers if (numbers.capacity < 5) {
print("The set size is small") } else { print("The set size is large") }

Output

The set size is large

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

Here, since there are only 3 elements in the set, numbers.capacity < 5 evaluates to true, so the statement inside the if block is executed.

Did you find this article helpful?