0

Hey I am trying to make a Set of Arrays and the arrays are to hold 2 integers

When I do

var points = Set<Array<Int>>();

I get this error:

Array<Int> does not conform to protocol hashable

I am trying to store a bunch of points like [x,y] ie. [33, 45]

I don't want to use a 2d array because the order of the points does not matter and I want to be able to remove points by their values (Set.remove[33,45])

luk2302
  • 55,258
  • 23
  • 97
  • 137
edstef
  • 3
  • 2
  • 1
    have you considered using a point object / class for that purpose instead of forcing arrays to do something they are not supposed to do? – luk2302 Feb 14 '16 at 18:37

1 Answers1

3

Instead of using arrays in such case, try creating a struct:

struct Point: Hashable {
    var x: Int
    var y: Int

    var hashValue: Int {
        get {
            return (31 &* x) &+ y
        }
    }
}

// Hashable inherits from Equatable, so you need to implement ==
func ==(lhs: Point, rhs: Point) -> Bool { 
    return lhs.x == rhs.x && lhs.y == rhs.y
}

var set = Set<Point>()
set.insert(Point(x: 33, y: 45))
print(set.count) // prints 1
set.remove(Point(x: 33, y: 45))
print(set.count) // prints 0
egor.zhdan
  • 4,555
  • 6
  • 39
  • 53
  • 1
    @luk2302 updated my post with `hashValue` implementation from http://stackoverflow.com/questions/24239295/writing-a-good-hashable-implementation-in-swift – egor.zhdan Feb 14 '16 at 18:59