Unique Objects inside a Array Swift

后端 未结 6 2133
小鲜肉
小鲜肉 2021-02-03 13:43

I have an array, with custom objects.

I Would like to pop the repeated objects, with the repeated properties:

let product = Product()
product.subCategory         


        
6条回答
  •  感情败类
    2021-02-03 13:49

    You can use Swift Set:

    let array = [product,product2,product3]
    
    let set = Set(array)
    

    You have to make Product conform to Hashable (and thus, Equatable) though:

    class Product : Hashable {
        var subCategory = ""
    
        var hashValue: Int { return subCategory.hashValue }
    }
    
    func ==(lhs: Product, rhs: Product) -> Bool {
        return lhs.subCategory == rhs.subCategory
    }
    

    And, if Product was a NSObject subclass, you have to override isEqual:

    override func isEqual(object: AnyObject?) -> Bool {
        if let product = object as? Product {
            return product == self
        } else {
            return false
        }
    }
    

    Clearly, modify those to reflect other properties you might have in your class. For example:

    class Product : Hashable {
        var category = ""
        var subCategory = ""
    
        var hashValue: Int { return [category, subCategory].hashValue }
    }
    
    func ==(lhs: Product, rhs: Product) -> Bool {
        return lhs.category == rhs.category && lhs.subCategory == rhs.subCategory
    }
    

提交回复
热议问题