How to get the length of a set in Swift

Overview

A set is a collection of unique elements. The length of a set is the number of elements present in that set. We can get the length of a set by using the count property.

Syntax

set.count

Return value

The value returned is an integer representing the number of elements a set instance contains.

Example

// create some sets
let evenNumbers : Set = [2, 4, 6, 8, 10, 12]
let oddNumbers : Set = [3, 5, 7, 9]
let emptySet = Set<String>()
// get their length
print(evenNumbers.count)
print(oddNumbers.count)
print(emptySet.count)

Explanation

  • Lines 2–4: We create some set variables and initialize them with values.
  • Lines 7–9: We get the lengths of the sets using the count property. Then, we print the results to the console.

Free Resources