Related Tags

swift
length
count
set
communitycreator

# How to get the length of a set in Swift

Theodore Kelechukwu Onyejiaku

### 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
Get the number of elements in a Set

### 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)
Get the length of a set in Swift

### 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.

RELATED TAGS

swift
length
count
set
communitycreator

CONTRIBUTOR

Theodore Kelechukwu Onyejiaku
RELATED COURSES

View all Courses

Keep Exploring

Learn in-demand tech skills in half the time