Unique Objects inside a Array Swift

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

    Here is an Array extension to return the unique list of objects based on a given key:

    extension Array {
        func unique(map: ((Element) -> (T)))  -> [Element] {
            var set = Set() //the unique list kept in a Set for fast retrieval
            var arrayOrdered = [Element]() //keeping the unique list of elements but ordered
            for value in self {
                if !set.contains(map(value)) {
                    set.insert(map(value))
                    arrayOrdered.append(value)
                }
            }
    
            return arrayOrdered
        }
    }
    

    using this you can so this

    let unique = [product,product2,product3].unique{$0.subCategory}
    

    this has the advantage of not requiring the Hashable and being able to return an unique list based on any field or combination

提交回复
热议问题