In more general cases, it collectionType.indexOf
will work if the object inside the array matches the protocol Equatable
. Since Swift String
already matches Equatable
, it drops AnyObject
to String
.
How to use a indexOf
collection type in a custom class? Swift 2.3
class Student{
let studentId: Int
let name: String
init(studentId: Int, name: String){
self.studentId = studentId
self.name = name
}
}
extension Student: Equatable{
}
func ==(lhs: Student, rhs: Student) -> Bool {
return lhs.studentId == rhs.studentId
}
func !=(lhs: Student, rhs: Student) -> Bool {
return !(lhs == rhs)
}
Now you can use it like this:
let john = Student(1, "John")
let kate = Student(2, "Kate")
let students: [Student] = [john, kate]
print(students.indexOf(John)) //0
print(students.indexOf(Kate)) //1
source
share