Swift Array – Check if Specific Element is Present
To check if an Array contains a specific element in Swift, call contains(_:)
method on the Array and pass the specific element as argument.
Syntax
The syntax to call contains() method to check if the specific element e
is present in the Array array
is
array.contains(e)
Examples
In the following program, we will take an integer array and check if the integer "8"
is present in this array.
main.swift
var array = [2, 4, 6, 8, 10] var e = 8 var isElementPresent = array.contains(e) print("Is elemnet present in array? \(isElementPresent)")
Output
Is elemnet present in array? true Program ended with exit code: 0
Since element 8
is present in the Array array
, contains() method returned true
.
Now, let us take an element such that it is not present in the array.
main.swift
var array = [2, 4, 6, 8, 10] var e = 15 var isElementPresent = array.contains(e) print("Is elemnet present in array? \(isElementPresent)")
Output
Is elemnet present in array? false Program ended with exit code: 0
Since e
is not present in array
, contains() method returned false
.
Conclusion
In this Swift Tutorial, we learned how to check if an Array contains a specific element in Swift programming.