Swift Check If an Array Contains an Object with Property

swift how to check if an array contains an object with a property

To check if a Swift array contains an object with a specific property:

  1. Have an array of elements.
  2. Specify a searching criterion.
  3. Call Array.contains() on the array with the criterion.

For instance, let’s find out if a student called Bob is in an array of students:

let has_bob = students.contains(where: { $0.name == "Bob" })

To understand how this works and to get the context, please read along.

Full Example with Context

First of all, let’s give context to the above line of code.

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]

You can use this approach to find out if a Student object with a specific name exists in the array:

let has_bob = students.contains(where: { $0.name == "Bob" }) // true

This returns true, as there is a student called “Bob” in the array.

How Does Array.contains() Method Work in Swift?

The Array.contains() method works such that:

  • It loops through the array of Student objects.
  • On each Student object, it stores the object temporarily to a variable $0.
  • Then it checks if the name of the student equals the name you are looking for.
  • If it encounters the name that matches wiht your search criterion, it returns true and stops looping.
  • If no matches are made, the contains() method continues until there are no more students left in the array.

Conclusion

Today you learned how to check if an array has an object with a property in Swift. You also learned how the Array.contains() method works by looping through an array of objects.

Thanks for reading. Happy coding!

Further Reading

50 Swift Interview Questions

iOS Development Tips

Share on facebook
Share on twitter
Share on linkedin

Leave a Comment

Your email address will not be published.