在扩展方法中使用数组的类型

Use Array's Type in Extension Method

我想做的是为数组创建一个扩展,以检查所有元素是否都是唯一的。我的计划是创建一个 Set 并检查 Set 的计数与 Array 的计数。但是,我不确定如何将 Set 的类型绑定到与 Array 相同的类型。

extension Array {
    func unique() -> Bool {
        var set = Set<self>()
        // Now add all the elements to the set
        return set.count == self.count
    }
} 

Array类型定义为

public struct Array<Element>

所以 Element 是通用占位符,您可以创建 具有与

相同元素类型的 Set
let set = Set<Element>()

但是你必须要求数组元素是Hashable:

extension Array where Element : Hashable { ... }

(为泛型定义扩展方法的可能性 在 Swift 2.)

中添加了对类型占位符的限制

最后,使用 set = Set(self) 自动推断集的类型:

extension Array where Element : Hashable {
    func unique() -> Bool {
        let set = Set(self)
        return set.count == self.count
    }
}