How to check if the array contains a given element in Swift?
Last Updated :
02 Jun, 2022
The Swift language supports different types of generic collections and an array is one of them. An array is an ordered collection that is used to keep the same type of data like int, float, string, etc., in an array you are not allowed to store the value of another type. It also keeps duplicate values of the same type. It can be mutable and immutable. When we assign an array to a variable, then that array is known as mutable whereas when we assign an array to a constant, then that array is known as immutable. In the Swift array, we check if the given array 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 array. It will return true if the given value is present in the array otherwise it will return false. This function is case sensitive, here Mohan and mohan are two different words.
Syntax:
arrayName.contains(ele)
Here,
arrayName is the object of the array 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 CreatorName = [ "Tina" , "Prita" , "Mona" , "Guri" , "Om" , "Rohit" ]
var result1 = CreatorName. contains ( "Mona" )
print (result1)
var result2 = CreatorName. contains ( "Sumit" )
print (result2)
|
Output:
true
false
Example 2:
Swift
import Swift
var CreatorRank = [34, 67, 12, 34, 90, 5, 67, 89, 2]
if (CreatorRank. contains (1))
{
print ( "1 is present in the array" )
}
else {
print ( "1 is not present in the array" )
}
if (CreatorRank. contains (67))
{
print ( "67 is present in the array" )
}
else {
print ( "67 is not present in the array" )
}
|
Output:
1 is not present in the array
67 is present in the array
Share your thoughts in the comments
Please Login to comment...