【问题标题】:Use Array's Type in Extension Method在扩展方法中使用数组的类型
【发布时间】:2015-10-16 16:05:53
【问题描述】:

我要做的是为数组创建一个扩展,以检查所有元素是否都是唯一的。我的计划是创建一个 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
    }
} 

【问题讨论】:

    标签: arrays swift set swift2


    【解决方案1】:

    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
        }
    } 
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-19
    • 1970-01-01
    • 2021-03-16
    • 2014-12-21
    • 2014-11-04
    相关资源
    最近更新 更多