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
     }
9
  • 1
    it is kind of unclear what are you trying to do... could you make it clearer? Commented Dec 28, 2016 at 8:35
  • 1
    Show us what you have try. Commented Dec 28, 2016 at 8:37
  • @AhmadF, please, see update Commented Dec 28, 2016 at 8:41
  • @NiravD please, see update Commented Dec 28, 2016 at 8:42
  • 1
    stackoverflow.com/q/31438210/3141234 Commented Dec 28, 2016 at 8:55

2 Answers 2

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.

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

Comments

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

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.