Swift How to Check If an Element Is in an Array

To check if an element is in an array in Swift, use the Array.contains() function.

For example, let’s check if the name “Alice” is in an array of names:

let names = ["Alice", "Bob", "Charlie"]

if names.contains("Alice") {
    print("Alice found")
}

Output:

Alice found

Let’s see a more advanced example.

Check If an Array Contains an Object with Specific Property

You can use the contains() function in a more advanced fashion to check if an array has an object with a specific property.

To do this:

  1. Create an array of objects.
  2. Define a searching function.
  3. Call Array.contains(where:) with the searching function.

Example

Given a custom Student class with a property name:

class Student {
    let name: String
    init(name: String) {
        self.name = name
    }
}

And an array of Student objects, each with a unique name:

let s1 = Student(name: "Alice")
let s2 = Student(name: "Bob")
let s3 = Student(name: "Charlie")

let students = [s1, s2, s3]

Your task is to figure out if a Student with the name “Alice” exists in the array.

Solution. Call the Array.contains(where:) function on the array of students with a function that checks if a Student is called “Alice”:

let has_alice = students.contains(where: { $0.name == "Alice" }) // Returns true

How Does It Work?

The Array.contains(where:) method in the above solution works such that:

  • It loops through the array of Student objects.
  • It assigns each Student object into a variable called $0 for the current iteration.
  • It checks if the name of that Student object equals to “Alice”.
  • If it is “Alice”, the contains() function returns true and stops looping.
  • If it does not find “Alice”, false is returned.

Now you understand how to use the contains() function in Swift in simple cases and in a bit more advanced cases.

Finally, let’s take a look at a common problem you may be trying to solve with the contains() function, when in reality, you should not.

How to Remove an Element from an Array in Swift

If you were searching for how to check if an element exists in an array, chances are you want to remove the element.

In Swift, you can remove an item from an array by following these three steps:

  1. Check if the array has the element.
  2. Find out the index of the element.
  3. Remove the element at the index.

However, you do not need to use the contains() method to check if there is a specific element in an array.

Instead, use:

  • Array.firstIndex(of:) function to find the index of the element you want to remove. This finds the first index of the specific value and returns the index. If no item is found it returns nil.
  • Array.remove(at:) to remove the element at that index.

For example:

var names = ["Alice", "Bob", "Charlie"]

// Remove "Alice" if exists:
if let index = names.firstIndex(of: "Alice") {
    names.remove(at: index)
}

print(names)

Output:

["Bob", "Charlie"]
Scroll to Top