-1

I created this singleton to access a shared array throughout my app:

class TranslationItems {
    var delegate: TranslationItemsDelegate?

    static let shared = TranslationItems()

    var array = [Translation]() {
        didSet {
            delegate?.newItemAdded()
        }
    }
}

The problem is that this allows for duplication (the array may contain multiple items with the same hashValue). If I check for duplication inside the didSet setter and then change the array there (for example by doing array = Array(Set(array))) that leads to an infinite loop.

How do I remove duplicates in my class?

3
  • Translation has to be hashable` Commented Dec 25, 2018 at 11:41
  • I confirm it is hashable already Commented Dec 25, 2018 at 11:59
  • stackoverflow.com/a/46519116/2303865 Commented Dec 25, 2018 at 12:33

1 Answer 1

4

If you want to avoid duplicates why don't you use a Set anyway (Translation must conform to Hashable)?

var set = Set<Translation>()

However if you want to keep the array a more efficient way is to add an add method which filters the duplicates, Translation must conform to Equatable

func add(object: Translation) {
    if !array.contains(object) {
       array.append(object)
       delegate?.newItemAdded()
    }
}

Making a Set from the Array and then convert it back to Array is unnecessarily expensive.

Sign up to request clarification or add additional context in comments.

6 Comments

array.contains will become expensive for a large number of elements.
@Carpsen90 Not as expensive as Array(Set(array)) 😉
Yes, that's like reaching for your ear with the wrong hand 😜Not sure why such answers are upvoted...
@Carpsen90 Most people especially the newbies are looking for the easiest/shortest solution which is not necessarily the most efficient.
[OT] @Cesare Marry is sposare 😉 Buon Natale.
|

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.