Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

count
elements
set
swift
communitycreator

How to get the number of elements in a Set without Count in Swift

Theodore Kelechukwu Onyejiaku

Overview

When we want to get the number of elements present in a set, we use the count property. Another property that can be used in its stead is underestimatedCount. It returns a value less than or equal to the number of elements in the set.

Syntax

set.underestimatedCount
Syntax for underestimatedCount

Return value

The value returned is an integer value.

Example

// create some sets
let evenNumbers : Set = [10, 2, 6, 8, 4]
let oddNumbers : Set = [11, 5, 7, 3, 9]
let first_names : Set = ["john", "jane", "henry", "mark"]

// get number of elements
print(evenNumbers.underestimatedCount)
print(oddNumbers.underestimatedCount)
print(first_names.underestimatedCount)
Get number of elements of a Set in Swift using underestimatedCount

Explanation

  • Line 2–4: We create some set instances and initialize them with some values.
  • Line 7–9: We use the underestimatedCount property to get the number of elements contained by the set values. Then we printed the values to the console.

RELATED TAGS

count
elements
set
swift
communitycreator

CONTRIBUTOR

Theodore Kelechukwu Onyejiaku
RELATED COURSES

View all Courses

Keep Exploring