How to count the elements of a Set in Swift?
Last Updated :
02 Jun, 2022
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
import Swift
var GEmpSalary: Set = [30000, 12200, 14000, 67800, 10000, 90000]
var result1 = GEmpSalary. count
print ( "Total number of elements in the set:" , result1)
var GEmployee = Set< Int >()
var result2 = GEmployee. count
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
import Swift
var GName: Set = [ "Tina" , "Prita" , "Mona" , "Guri" , "Om" , "Rohit" ]
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
Share your thoughts in the comments
Please Login to comment...