0

I have two arrays, I am trying to check if contents of one is present in the other array. However, I got a crash with error

Thread 1: Fatal error: Duplicate elements of type 'Report' were found in a Set.
This usually means either that the type violates Hashable's requirements, or
that members of such a set were mutated after insertion.

this is what I am using to check

extension Array where Element: Hashable {

    func set() -> Set<Array.Element> {
        return Set(self)
    }

    func isSubset(of array: Array) -> Bool {
        self.set().isSubset(of: array.set())
    }

    func isSuperset(of array: Array) -> Bool {
        self.set().isSuperset(of: array.set())
    }

    func commonElements(between array: Array) -> Array {
        let intersection = self.set().intersection(array.set())
        return intersection.map({ $0 })
    }

    func hasCommonElements(_ array: Array) -> Bool {
        return self.commonElements(between: array).count >= 1 ? true : false
    }
}

How can I correct this or if there is an alternative.

I have a variable allTransactionHistory which is of type [Report]

variable reports is new data fetched from an API which is also of type [Report]

allTransactionHistory.hasCommonElements(reports)

struct Report: Hashable {

}
King
  • 1,885
  • 3
  • 27
  • 84
  • I do not fully understand you. – King Apr 26 '21 at 14:40
  • Which function generates the error and can you post a reproducible example? – Joakim Danielson Apr 26 '21 at 14:59
  • This function `commonElements` and this is the line `self.set().intersection(array.set())` – King Apr 26 '21 at 15:00
  • 1
    And a reproducible example...? Maybe add the definition of Report – Joakim Danielson Apr 26 '21 at 15:03
  • Check the explanation I added. – King Apr 26 '21 at 15:06
  • Unfortunately that isn't very helpful, I would debug this or use print statements to see if more than one of the Report objects in either array has the same `hashValue` – Joakim Danielson Apr 26 '21 at 15:12
  • The first sent of values are stored in the `var allTransactionHistory` when that endpoint is called again, then I check if the new values which is `var reports` contains similar values as the ones previously stored in the `var allTransactionHistory` – King Apr 26 '21 at 15:15
  • Could you make `dump(reports)` and `dump(allTransactionHistory)` in order to check if these arrays contain duplicative elements? If so it will fail on the step of transforming into a set – grigorevp Apr 26 '21 at 15:32
  • Is `Report` a class? See if this helps you: https://stackoverflow.com/a/55677727/968155 – New Dev Apr 26 '21 at 21:10

0 Answers0