Check if an element is in an Array in Swift


In this Swift tutorial, you are going to learn how to check if an element is exist in a Swift Array or not.

To check if an item exists or not in an array we will use the Swift contains() method. This method will return a boolean value true or false.

If the returned value is true, then it indicates that the array contains the given element that you pass to the method. Otherwise, it will return false which indicates the given element is not available in the array.

Below is the basic syntax of using the contains() method:

array.contains(element)

In the above syntax element is the element that we want to find in the array.

Below is an example where you can see how to use the Swift contains() method:

let colors = ["Red", "green", "Blue"]

let result = colors.contains("Blue")

print(result)

Output:

true

contains() method with if statement

Now see the example below where we are checking if a specific element is in the array using the Swift if statement:

let cities = ["London", "Berlin", "Chicago", "─░stanbul", "Doha"]

if cities.contains("Berlin") {
    print("Berlin found")
}

Output:

Berlin found

In the above example, we have created an array cities that contains the name of some cities. We are using the contains() method and passing the array item to find out if it is available in the array or not.

contains() method with if…else statement

Below we are using contains() method with the Swift if…else statement to find out if the specific array item exists in the array or not:

let cities = ["London", "Berlin", "Chicago", "─░stanbul", "Doha"]

if cities.contains("Berlin") {
    print("Berlin found")
} else {
    print("Berlin not found")
}

Output:

true