无法使用types为“(ChecklistItem)”的参数列表调用“indexOf”

当我正在写代码从数组中find一个项目使用indexOf时,它显示了上述错误。 这是我的代码:

func addItemViewController(controller: AddItemViewController, didFinishEditingItem item: ChecklistItem) { if let index = items.indexOf(item) { let indexPath = NSIndexPath(forRow: index, inSection: 0) if let cell = tableView.cellForRowAtIndexPath(indexPath) { configureTextForCell(cell, withChecklistItem: item) } } 

为了使用indexOfChecklistItem必须采用Equatable协议 。 只有通过采用这个协议,列表才能将项目与其他项目进行比较以find所需的索引

indexOf只能应用于Equatabletypes的集合,您的ChecklistItem不符合Equatable协议(有一个==运算符)。

为了能够使用indexOf将其添加到全局范围中包含ChecklistItem类的文件中:

 func ==(lhs: ChecklistItem, rhs: ChecklistItem) -> Bool { return lhs === rhs } 

请注意,它将通过比较内存中的实例地址进行比较。 您可能希望通过比较类的成员来检查平等。

我意识到这个问题已经有了一个可以接受的答案,但是我发现了另一个会导致这个错误的案例,所以可能会帮助别人。 我正在使用Swift 3。

如果你创build了一个集合并且允许这个types被推断出来,你也可能会看到这个错误。

例:

 // UITextfield conforms to the 'Equatable' protocol, but if you create an // array of UITextfields and leave the explicit type off you will // also see this error when trying to find the index as below let fields = [ tf_username, tf_email, tf_firstname, tf_lastname, tf_password, tf_password2 ] // you will see the error here let index = fields.index(of: textField) // to fix this issue update your array declaration with an explicit type let fields:[UITextField] = [ // fields here ] 

可能的原因是你没有告诉ChecklistItemtypes它是可以等化的,也许你忘了提到ChecklistItem类是从NSObjectinheritance的。

 import Foundation class ChecklistItem: NSObject { var text = "" var checked = false func toggleChecked() { checked = !checked } } 

NSObject采用或符合可平等协议

Swift 4和Swift 3中 ,更新你的数据模型以符合“Equatable”协议,并实现lhs = rhs方法,只有这样你才能使用“.index(of:…)”,因为你正在比较你的自定义目的

 Eg: class Photo : Equatable{ var imageURL: URL? init(imageURL: URL){ self.imageURL = imageURL } static func == (lhs: Photo, rhs: Photo) -> Bool{ return lhs.imageURL == rhs.imageURL } } 

用法:

 let index = self.photos.index(of: aPhoto)