1

So, I have loop, where I get [Int] and that Array may has only one element, may has several elements. That arrays may be the same and may be different.

I'd like to create Array of unique of arrays [Int]. How to do it? When I try to create by Set I see that

[Int] not hashable

my code:

for i in 0..<someData.count {

      someData?[i].db.value(forKey: "value") as! [Int] // here I get [Int]

      //here I'd like to create an array of unique arrays from from the line above
     }
Vadim Nikolaev
  • 2,132
  • 17
  • 34

2 Answers2

1
var values:[Int] = [] {
    didSet{
        var uniqueValues = [Int]()
        var addedValues = Set<Int>()
        for value in values {
            if !addedValues.contains(value) {
                addedValues.insert(value)
                uniqueValues.append(value)
            }
        }
        values = uniqueValues
    }
}

values is your array which will hold only unique values.Hope this is what you are looking for.

Aman Gupta
  • 985
  • 1
  • 8
  • 18
1

You can implement your own Hashable array too

import Foundation

internal struct HashableIntArray: Hashable {
    var value: [Int]
    var hashValue: Int { return value.reduce(0, +).hashValue }
}

internal func == (lhs:HashableIntArray,rhs: HashableIntArray) -> Bool {
    return lhs.value == rhs.value
}

let array = [HashableIntArray(value: [1,1,2]), HashableIntArray(value: [1,2,2]), HashableIntArray(value: [1,1,2])]

let set = Set(array)
print(array) // [HashableIntArray(value: [1, 1, 2]), HashableIntArray(value: [1, 2, 2]), HashableIntArray(value: [1, 1, 2])]
print(set) // [HashableIntArray(value: [1, 2, 2]), HashableIntArray(value: [1, 1, 2])]
Niko Adrianus Yuwono
  • 11,012
  • 8
  • 42
  • 64