将唯一对象添加到数组

时间:2015-11-06 04:30:19

标签: ios swift

我已经阅读了所有关于Set的内容,但由于我的物品不可清洗(这种情况很常见),因此它们不适合该法案。

我有Product

class Product: Object {

    dynamic var sku: String!
    dynamic var name: SomeUnhashableType!
    dynamic var weight: String!    
}

let uniqueProductArray = [productOne, productTwo, productThree]

uniqueProductArray.append(productOne)

我已经阅读了关于使用containsindexOffilter等的信息。但是他们都使用谓词,我喜欢非谓词方法。< / p>

什么是阻止重复对象附加到数组的最优雅方式?

1 个答案:

答案 0 :(得分:2)

通过将该协议添加到定义并为您的班级实施Equatable来创建班级==。然后,您可以在不使用谓词版本的情况下使用contains

class Product: Object, Equatable {
    dynamic var sku: String!
    dynamic var name: String!
    dynamic var weight: String!
}

func == (lhs: Product, rhs: Product) -> Bool {
    return lhs.sku == rhs.sku && lhs.name == rhs.name && lhs.weight == rhs.weight
}

let productOne = Product()
productOne.sku = "one"
productOne.name = "name"
productOne.weight = "heavy"

let productTwo = Product()
productTwo.sku = "two"
productTwo.name = "name"
productTwo.weight = "heavy"

let productThree = Product()
productThree.sku = "three"
productThree.name = "name"
productThree.weight = "heavy"

var uniqueProductArray = [productOne, productTwo]

if !uniqueProductArray.contains(productThree) {
    uniqueProductArray.append(productThree)
}
相关问题