无法使用类型'(ChecklistItem)'的参数列表调用'indexOf'

sha*_*ria 21 iphone xcode ios swift

当我使用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)
        }
    }
Run Code Online (Sandbox Code Playgroud)

Zel*_* B. 34

为了使用indexOfChecklistItem,必须采取Equatable协议.只有采用此协议,列表才能将项目与其他项目进行比较,以找到所需的索引


Fan*_*ude 14

indexOf只能应用于Equatable类型集合,您ChecklistItem不符合Equatable协议(有==运营商).

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

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

Swift3: 
public static func ==(lhs: Place, rhs: Place) -> Bool {
        return lhs === rhs
    }
Run Code Online (Sandbox Code Playgroud)

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


Nai*_*hta 5

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
    }
}
Run Code Online (Sandbox Code Playgroud)

用法:

let index = self.photos.index(of: aPhoto)
Run Code Online (Sandbox Code Playgroud)