Open In App

How to count the elements of a Set in Swift?

Last Updated : 02 Jun, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

Swift supports the different types of generic collections and set is one of them. A set is used to store unordered values of the same type. It means you are not allowed to keep different types in the set. You can use a set instead of an array if the order of the values is not defined or you want to store unique values. It doesn’t keep duplicate values, it always keeps unique values in it. It generally uses a hash table to store the elements. In the Swift set, we can count the elements of the set. To do this we use the count property of the set. This property is used to count the total number of values available in the specified set.

Syntax:

setName.count

Here, 

setName is the object of the set class.

Return Value: It will return the total number of values present in the given set. 

Example 1:

Swift




// Swift program to find the total number of elements in the set
import Swift
  
// Creating an set of EmployeeSalary
// Here the set is of int type
var GEmpSalary: Set = [30000, 12200, 14000, 67800, 10000, 90000]
  
// Finding the total number of elements
// Using count property
var result1 = GEmpSalary.count
  
// Displaying the result
print("Total number of elements in the set:", result1)
  
// Creating an empty set of int type
var GEmployee = Set<Int>()
  
// Finding the total number of elements
// Using count property
var result2 = GEmployee.count
  
// Displaying the result
print("Total number of elements in the set:", result2)


Output:

Total number of elements in the set: 6
Total number of elements in the set: 0

Example 2:

Swift




// Swift program to find the total number of elements in the set
import Swift
  
// Creating an set of Employee Name
// Here the set is of string type
var GName: Set = ["Tina", "Prita", "Mona", "Guri", "Om", "Rohit"]
  
// Using count property
if (GName.count > 2)
{
    print("Set contains more employee name")
}
else
{
    print("Set contains less employee name")
}


Output:

Set contains more employee name


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads