Unique Objects inside a Array Swift

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

    If your class conforms to protocol Hashable and you would like to keep the original array order you can create an extension as follow:

    extension Array where Element: Hashable {
        var uniqueElements: [Element] {
            var elements: [Element] = []
            for element in self {
                if let _ = elements.indexOf(element) {
                    print("item found")
                } else {
                    print("item not found, add it")
                    elements.append(element)
                }
            }
            return elements
        }
    }
    

提交回复
热议问题