Unique Objects inside a Array Swift

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

    If Product conforms to Equatable, where a product is equal based on it's subcategory (and you don't care about order), you can add the objects to a set, and take an array from that set:

    let array = [product,product2,product3]
    let set = NSSet(array: array)
    let uniqueArray = set.allObjects
    

    or

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

提交回复
热议问题