Vadim Nikolaev
Vadim Nikolaev

Reputation: 2132

Create Array of unique Arrays [Int] in swift

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
     }

Upvotes: 1

Views: 205

Answers (2)

Niko Adrianus Yuwono
Niko Adrianus Yuwono

Reputation: 11112

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])]

Upvotes: 1

Aman Gupta
Aman Gupta

Reputation: 985

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.

Upvotes: 1

Related Questions