How to check if an element is contained in an array in Swift

Overview

We can check if a certain element exists in an array by using the contains() method.

Syntax

arr.contains(elem)

Parameters

arr: This is the array we want to check to see if it contains a certain element.

elem: This is the element we want to check to see if it exists in the array arr.

Return value

A Boolean value is returned. true is returned if the element elem exists in array arr. Otherwise, it returns false.

Code example

// create arrays
let gnaam = ["Google", "Netflix", "Amazon", "Apple", "Meta"]
let vowels = ["a", "e", "i", "o", "u"]
let languages = ["C", "Swift", "Java"]
// check if some elements are present
print(gnaam.contains("Facebbok")); // false
print(gnaam.contains("Meta")) // true
print(vowels.contains("a")) // true
print(vowels.contains("z")) // false
print(languages.contains("Python")) // false
print(languages.contains("C")) // true

Explanation

  • In lines 2 to 4, we create the arrays gnaam, vowels, and languages.
  • In lines 7 to 12, we invoke the contains() method on the arrays we created, and pass some parameters to it. We then print the results on the console.

Free Resources