Open In App

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

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

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




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


Output:

true
false

Example 2:

Swift




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


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

Similar Reads