Open In App

How to check if the set contains a given element in Swift?

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

Swift supports the generic collection 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 store different types in the set, e.g. a set is of int type then you can only store values of int type not of string type. A is used set instead of an array if the order of the values is not defined or you want to store unique values. Set doesn’t keep duplicate values, it always keeps unique values and uses a hash table to store the elements. In the Swift Set, we can easily check if the given set contains the specified element to not. To do this task we use the contains() function. This function is used to check if the given element is present or not in the specified set. It will return true if the given value is present in the set otherwise it will return false. This function is case sensitive, here Mohan and mohan are two different words.

Syntax:

setName.contains(ele)

Here,

setName is the object of the set class and the parameter ele represent the element. 

Return Value: This function will return true if the given array contains the specified value otherwise it will return false. 

Example 1:

Swift




// Swift program to check if the specified element
// is present in the set or not
import Swift
  
// Creating an set of Creator rank
// Here the set is of int type
var CreatorRank : Set = [34, 67, 12, 34, 90, 5, 67, 89, 2]
  
// Checking if the given is present 
// in the set or not
if (CreatorRank.contains(1))
{
    print("1 is present in the set")
}
else{
    print("1 is not present in the set")
}
  
// Checking if the given number is present in 
// the set or not
if (CreatorRank.contains(67))
{
    print("67 is present in the set")
}
else{
    print("67 is not present in the set")
}


Output:

1 is not present in the set
67 is present in the set

Example 2: 

Swift




// Swift program to check if the specified element
// is present in the set or not
import Swift
  
// Creating an set of Creator name
// Here the set is of string type
var CreatorName : Set = ["Tina", "Prita", "Mona", "Guri", "Om", "Rohit"]
  
// Checking if Mona is present in the given set or not
var result1 = CreatorName.contains("Mona")
  
// Displaying result
print(result1)
  
// Checking if Sumit is present in the given set or not
var result2 = CreatorName.contains("Sumit")
  
// Displaying result
print(result2)


Output:

true
false


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

Similar Reads