Sling Academy
Home/Swift/Swift: Counting the Number of Elements in a Set

Swift: Counting the Number of Elements in a Set

Last updated: May 09, 2023

In Swift, you can count the number of elements in a set by using the count property.

Example:

let words = Set(["Sling", "Academy", "Swift", "iOS"])
let count = words.count
print("The set contains \(count) elements.")

Output:

The set contains 4 elements.

An empty set is a set that contains no elements. You can check whether a set is empty or not like so:

var numbers = Set<Int>()
if(numbers.count == 0){
    print("Empty")
} else {
    print("Not Empty")
}

Output:

Empty

A better solution to check if a set is empty is to use the isEmpty property as shown below:

var numbers = Set<Int>()
if(numbers.isEmpty){
    print("Empty")
} else {
    print("Not Empty")
}

This concise tutorial ends here. Happy coding & have a nice day!

Next Article: Swift: Checking if a Set Contains a Specific Element

Previous Article: Adding new Elements to a Set in Swift

Series: Collection data types in Swift

Swift

You May Also Like

  • How to Find the Union of 2 Sets in Swift
  • How to Find the Intersection of 2 Sets in Swift
  • Subtracting 2 Sets in Swift (with Examples)
  • Swift: Removing Elements from a Set (4 Examples)
  • Swift: Checking if a Set Contains a Specific Element
  • Adding new Elements to a Set in Swift
  • How to Create a Set in Swift
  • Swift: Converting a Dictionary into an Array
  • Merging 2 Dictionaries in Swift
  • Swift: Check if a key exists in a dictionary
  • Swift: Removing a key-value pair from a dictionary
  • Swift: Adding new key-value pairs to a dictionary
  • Swift: Counting Elements in a Dictionary
  • Swift: Ways to Calculate the Product of an Array
  • Swift: How to Convert an Array to JSON
  • Swift: Different ways to find the Min/Max of an array
  • Swift: 4 Ways to Count the Frequency of Array Elements
  • How to Compare 2 Arrays in Swift (Basic & Advanced)
  • Swift: 5 Ways to Iterate over an Array