Unique Objects inside a Array Swift

后端 未结 6 2130
小鲜肉
小鲜肉 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 14:09

    class Product {
        var subCategory: String = ""
    }
    
    let product = Product()
    product.subCategory = "one"
    
    let product2 = Product()
    product2.subCategory = "two"
    
    let product3 = Product()
    product3.subCategory = "two"
    
    let array = [product,product2,product3]
    
    extension Product : Hashable {
        var hashValue: Int {
            return subCategory.hashValue
        }
    }
    func ==(lhs: Product, rhs: Product)->Bool {
        return lhs.subCategory == rhs.subCategory
    }
    
    let set = Set(array)
    set.forEach { (p) -> () in
        print(p, p.subCategory)
    }
    /*
    Product one
    Product two
    */
    

    if an item is part of set or not doesn't depends on hashValue, it depends on comparation. if your product conform to Hashable, it should conform to Equatable. if you need that the creation of the set depends solely on subCategory, the comparation should depends solely on subCategory. this can be a big trouble, if you need to compare your products some other way

提交回复
热议问题