Unique Objects inside a Array Swift

后端 未结 6 2135
小鲜肉
小鲜肉 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:56

    Here is a KeyPath based version of the Ciprian Rarau' solution

    extension Array {
        func unique(by keyPath: KeyPath) -> [Element] {
            var set = Set()
            return self.reduce(into: [Element]()) { result, value in
                guard !set.contains(value[keyPath: keyPath]) else {
                    return
                }
                set.insert(value[keyPath: keyPath])
                result.append(value)
            }
        }
    }
    

    example usage:

    let unique = [product, product2, product3].unique(by: \.subCategory)
    

提交回复
热议问题