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 protocolhashable
I am trying to store a bunch of points like [x,y] ie. [33, 45]
[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]
)
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.