To check if a Swift array contains an object with a specific property:
- Have an array of elements.
- Specify a searching criterion.
- 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
About the Author
- I'm an entrepreneur and a blogger from Finland. My goal is to make coding and tech easier for you with comprehensive guides and reviews.
Recent Posts
Artificial Intelligence2023.05.16Humata AI Review (2023): Best PDF Analyzer (to Understand Files)
Python2023.05.139 Tips to Use ChatGPT to Write Code (in 2023)
Artificial Intelligence2023.04.1114 Best AI Website Builders of 2023 (Free & Paid Solutions)
JavaScript2023.02.16How to Pass a Variable from HTML Page to Another (w/ JavaScript)
Your article helped me a lot, is there any more related content? Thanks!
Your point of view caught my eye and was very interesting. Thanks. I have a question for you.