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 arrayslet gnaam = ["Google", "Netflix", "Amazon", "Apple", "Meta"]let vowels = ["a", "e", "i", "o", "u"]let languages = ["C", "Swift", "Java"]// check if some elements are presentprint(gnaam.contains("Facebbok")); // falseprint(gnaam.contains("Meta")) // trueprint(vowels.contains("a")) // trueprint(vowels.contains("z")) // falseprint(languages.contains("Python")) // falseprint(languages.contains("C")) // true
Explanation
- In lines 2 to 4, we create the arrays
gnaam,vowels, andlanguages. - 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.