How to check if the set contains a given element in Swift?
Last Updated :
02 Jun, 2022
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
import Swift
var CreatorRank : Set = [34, 67, 12, 34, 90, 5, 67, 89, 2]
if (CreatorRank. contains (1))
{
print ( "1 is present in the set" )
}
else {
print ( "1 is not present in the set" )
}
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
import Swift
var CreatorName : Set = [ "Tina" , "Prita" , "Mona" , "Guri" , "Om" , "Rohit" ]
var result1 = CreatorName. contains ( "Mona" )
print (result1)
var result2 = CreatorName. contains ( "Sumit" )
print (result2)
|
Output:
true
false
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...