You want to iterate over an array of custom objects, and need to tell whether two objects are equal. You're not concerned with two objects being identical in memory, but equivalent based on your own definition.
class Student {
var studentId = 0
var firstName = "Bob"
}
extension Student : Equatable {}
func ==(lhs: Student, rhs: Student) -> Bool {
return lhs.studentId == rhs.studentId
}
A few things to note:
- You conform to the
Equatable
protocol, but you don't actually implement any methods - It's just a function declaration. Instead of this,
func foo(){}
do this:func ==(){}
- This equality function is global. Don't put it inside the class.
Now you can iterate over the objects.
if contains(studentArray, studentB) {
// B is in the Array
}