在更一般的情況下,當一個數組裏面的對象都符合Equatable
協議collectionType.indexOf
會工作。由於Swift String
已符合Equatable
,因此將AnyObject
轉換爲String
將刪除該錯誤。
如何在集合類型自定義類上使用indexOf
?雨燕2.3
class Student{
let studentId: Int
let name: String
init(studentId: Int, name: String){
self.studentId = studentId
self.name = name
}
}
//notice you should implement this on a global scope
extension Student: Equatable{
}
func ==(lhs: Student, rhs: Student) -> Bool {
return lhs.studentId == rhs.studentId //the indexOf will compare the elements based on this
}
func !=(lhs: Student, rhs: Student) -> Bool {
return !(lhs == rhs)
}
現在你可以使用它像這樣
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
你爲什麼不使用'[字符串]',你應該很少使用'AnyObject',特別是在迅速!你應該總是指定你的數組持有什麼! – AaoIi
'AnyObject'是「未指定」的佔位符。該數組顯然是一個字符串數組,所以只需刪除註釋'[AnyObject]'。編譯器會推斷正確的事情。 – vadian
如果數組是一個在目標C類中定義的NSArray,該怎麼辦? –