Swift Extension of Array with Equatable Elements Cannot Call Index(of:)

吃可爱长大的小学妹 提交于 2019-12-01 12:34:45

The problem is you're defining a new generic placeholder T in your method – which is not necessarily the same type as Element. Therefore when you say newArray.index(of: element), you're trying to pass an Element into a argument of type T.

The solution therefore is to simply to type the newArray: parameter as [Element]:

extension Array where Element : Equatable {
    func deletedIndicies(byKeeping elementsToKeep: [Element]) -> [Int] {
        // ...
    }
}

As a side note, this method could also be implemented as:

extension Array where Element : Equatable {

    func deletedIndicies(byKeeping elementsToKeep: [Element]) -> [Int] {

        // use flatMap(_:) to iterate over a sequence of pairs of elements with indices,
        // returning the index of the element, if elementsToKeep doesn't contains it,
        // or nil otherwise, in which case flatMap(_:) will filter it out.
        return self.enumerated().flatMap {
            elementsToKeep.contains($1) ? nil : $0
        }
    }
}

Also, if you change the constraint on Element to Hashable, this could be also be implemented in O(n), rather than O(n * m) time, which could potentially be desirable:

extension Array where Element : Hashable {

    func deletedIndicies(byKeeping elementsToKeep: [Element]) -> [Int] {

        // create new set of elements to keep.
        let setOfElementsToKeep = Set(elementsToKeep)

        return self.enumerated().flatMap {
            setOfElementsToKeep.contains($1) ? nil : $0
        }
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!