通用参数无法快速推断

Aru*_*r P 4 generics ios swift

我为不同的项目编写了一个Array扩展

extension Array {
    func distinct<T: Equatable>() -> [T]{
        var unique = [T]()
        for i in self{
            if let item = i as? T {
                if !unique.contains(item){
                    unique.append(item)
                }
            }
        }
        return unique
    }
}
Run Code Online (Sandbox Code Playgroud)

并尝试调用此函数,如下所示

let words = ["pen", "Book", "pencile", "paper", "Pin", "Colour Pencile", "Marker"]
words.distinct()
Run Code Online (Sandbox Code Playgroud)

但它给出错误"通用参数'T'无法推断迅速"

Gre*_*reg 14

您可以通过告诉编译器您期望的内容来消除此错误:

let a: [String] = words.distinct()
Run Code Online (Sandbox Code Playgroud)

问题是编译器不知道通用T是什么.更好的解决方案是告诉编译器您为其元素为Equatable的所有数组定义了不同的函数:

extension Array where Element : Equatable {
    func distinct() -> [Element]{
        var unique = [Element]()
        for i in self{
            if let item = i as? Element {
                if !unique.contains(item){
                    unique.append(item)
                }
            }
        }
        return unique
    }
}
Run Code Online (Sandbox Code Playgroud)