How to check if an element is in an array?


This article will explain how you can check if an element exists in an array or not in the Swift language.

There are several ways to check if an element is in an array in Swift −

Using the contains method

The contains(_:) method returns true if an array contains the target element. This method can only be used with arrays whose elements conform to the Equatable protocol.

Here is an example where we use contains with an array of strings. String conforms to the Equatable protocol, so we can use the contains method here.

Algorithm

  • Step 1 - Create an input array of strings

  • Step 2 - Call the contains() method by passing the target element

  • Step 3 - The contains() method returns a bool value

Example

import Foundation
let languages = ["PHP", "Java", "Python", "JavaScript", "Swift", "Objective-C"]
let targetElement = "Swift"
print ("Given array =",languages,"\nElement to search =",targetElement)

if languages.contains(targetElement) {
    print("\(targetElement) is in the array.")
} else {
    print("\(targetElement) is not in the array.")
}

Output

Given array = ["PHP", "Java", "Python", "JavaScript", "Swift", "Objective-C"] 
Element to search = Swift
Swift is in the array.

Using the contains(where:) method

contains(where:) is a method of the Sequence protocol in Swift that returns a Boolean value indicating whether the sequence contains an element that satisfies the given predicate.

Algorithm

  • Step 1 - Create an input array of strings

  • Step 2 - Call the contains(where:) method

  • Step 3 - Check for the target element in the where closure inside contains(where:) function

  • Step 4 - The contains(where:) method returns a bool value

Example

Here's an example of how you can use contains(where:) to check if an array of strings contains a string −

import Foundation
let languages = ["PHP", "Java", "Python", "JavaScript", "Swift", "Objective-C"]
let targetElement = "Swift"
print ("Given array =",languages,"\nElement to search =",targetElement)
if languages.contains(where: { $0 == targetElement }) {
    print("\(targetElement) is in the array.")
} else {
    print("\(targetElement) is not in the array.")
}

Output

Given array = ["PHP", "Java", "Python", "JavaScript", "Swift", "Objective-C"] 
Element to search = Swift
Swift is in the array.

Example

You can also use contains(where:) to search for an element in an array of custom types, as long as you provide a predicate that returns a Boolean value indicating whether the element satisfies a certain condition. For example,

import Foundation
struct Student {
    let name: String
    let score: Int
}
let students: [Student] = [Student(name: "John", score: 80),
   Student(name: "Tina", score: 75),
   Student(name: "Bob", score: 89),
   Student(name: "Alice", score: 67)]
print(students)                         
    
if students.contains(where: { $0.score > 80 }) {
    print("The student array contains a student who scored more than 80%.")
} else {
    print("The student array does not contain any students who scored more than 80%.")
}

Output

[main.Student(name: "John", score: 80), main.Student(name: "Tina", score: 75), main.Student(name: "Bob", score: 89), main.Student(name: "Alice", score: 67)]
The student array contains a student who scored more than 80%.

Using the filter method

The filter method is a higher-order function in Swift that allows you to create a new array from an existing one by including only those elements that satisfy a certain condition.

Algorithm

  • Step 1 - Create an input array of strings

  • Step 2 - Call the filter() function

  • Step 3 - Check for the target element in the closure inside the filter() function

  • Step 4 - The filter() function returns a new array of search elements

  • Step 5 - Check whether the result array is empty or not

Example

Here's an example of how you can use a filter to check whether an element is in an array or not −

let languages = ["PHP", "Java", "Python", "JavaScript", "Swift", "Objective-C"]
let targetElement = "Swift"
print ("Given array =",languages,"\nElement to search =",targetElement)
let filteredElements = languages.filter({ $0 == targetElement })
if filteredElements.isEmpty == false {
    print("\(targetElement) is in the array.")
} else {
    print("\(targetElement) is not in the array.")
}

Output

Given array = ["PHP", "Java", "Python", "JavaScript", "Swift", "Objective-C"] 
Element to search = Swift
Swift is in the array.

Using the firstIndex(of:) method

A firstIndex(of:) is a method of the RandomAccessCollection protocol in Swift that returns the index of the first element in the collection that is equal to a given element, or nil if the element is not found.

Here's an example of how you can use firstIndex(of:) to find the index of a specific element in an array −

Algorithm

  • Step 1 - Create an input array of strings

  • Step 2 - Call the firstIndex() function

  • Step 3 - Return the index of the target element if it contains in the input array

  • Step 4 - The firstIndex() function returns the first index

  • Step 5 - Check whether the first index is valid or not

Example

import Foundation
let languages = ["PHP", "Java", "Python", "JavaScript", "Swift", "Objective-C"]
let targetElement = "Swift"
print ("Given array =",languages,"\nElement to search =",targetElement)
if let index = languages.firstIndex(of: targetElement) {
    print("\(targetElement) is in the array at index \(index).")
} else {
    print("\(targetElement) is not in the array.")
}

Output

Given array = ["PHP", "Java", "Python", "JavaScript", "Swift", "Objective-C"] 
Element to search = Swift
Swift is in the array at index 4

Using a for loop

Algorithm

  • Step 1 - Create an input array of strings

  • Step 2 - Perform a for loop over the input array

  • Step 3 - Check for the target element if it contains in the input array

  • Step 4 - Break the for-loop execution if the target element is found

Example

import Foundation
let languages = ["PHP", "Java", "Python", "JavaScript", "Swift", "Objective-C"]
let targetElement = "Swift"
print ("Given array =",languages,"\nElement to search =",targetElement)
for language in languages {
    if language == targetElement {
        print("\(targetElement) is in the array.")
        break
    }
}

Output

Given array = ["PHP", "Java", "Python", "JavaScript", "Swift", "Objective-C"] 
Element to search = Swift
Swift is in the array.

Conclusion

We have different methods to check whether an element is in an array. Each method has its own time complexity for determining the result. You can use any method according to your requirements.

Updated on: 07-Sep-2023

65 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements