本文介绍了数组Swift中的唯一对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个带有自定义对象的数组。
I have an array, with custom objects.
我想用重复的属性弹出重复的对象:
I Would like to pop the repeated objects, with the repeated properties:
let product = Product()
product.subCategory = "one"
let product2 = Product()
product2.subCategory = "two"
let product3 = Product()
product3.subCategory = "two"
let array = [product,product2,product3]
在这种情况下,弹出 product2或product3
推荐答案
您可以使用Swift 设置
:
You can use Swift Set
:
let array = [product,product2,product3]
let set = Set(array)
你必须使产品
符合 Hashable
(因此, Equatable
)虽然:
You have to make Product
conform to Hashable
(and thus, Equatable
) though:
class Product : Hashable {
var subCategory = ""
var hashValue: Int { return subCategory.hashValue }
}
func ==(lhs: Product, rhs: Product) -> Bool {
return lhs.subCategory == rhs.subCategory
}
,如果 Product
是 NSObject
子类,则必须覆盖 isEqual
:
And, if Product
was a NSObject
subclass, you have to override isEqual
:
override func isEqual(object: AnyObject?) -> Bool {
if let product = object as? Product {
return product == self
} else {
return false
}
}
显然,修改它们以反映您班级中可能包含的其他属性。例如:
Clearly, modify those to reflect other properties you might have in your class. For example:
class Product : Hashable {
var category = ""
var subCategory = ""
var hashValue: Int { return [category, subCategory].hashValue }
}
func ==(lhs: Product, rhs: Product) -> Bool {
return lhs.category == rhs.category && lhs.subCategory == rhs.subCategory
}
这篇关于数组Swift中的唯一对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!