0

I've read all about Sets and they don't fit the bill because my objects are not hashable (which is quite common).

I have a Product class

class Product: Object {

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

let uniqueProductArray = [productOne, productTwo, productThree]

uniqueProductArray.append(productOne)

I've read about using contains, indexOf, filter, etc. But they all use predicates and I'd like a non-predicate method.

What's the most elegant way of blocking duplicate objects from being appended to an array?

7
  • If your object is composed of hashable objects like String, why not just implement Hashable and use a set? You can just concatenate your strings together and call hash on the result for your hash implementation. Commented Nov 6, 2015 at 4:43
  • @CharlesA. Edited cause thats not really the question, besides why not just use a set if they're hashable ? Commented Nov 6, 2015 at 4:46
  • @rayjohn: use the 'contains' for check the object already contains in the array the add the same. Commented Nov 6, 2015 at 4:47
  • @VineeshTP that does not work Commented Nov 6, 2015 at 4:48
  • 2
    Out of curiosity, what type isn't hashable? Your implementation of hash and isEqual: can do whatever you want (within required limits). Commented Nov 6, 2015 at 5:15

1 Answer 1

2

Make your class Equatable by adding that protocol to the definition and by implementing == for your class. Then you can use contains without using the predicate version:

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)
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.