As can be seen from the forum history, many people have suggested ways to make it possible to conform tuple types to protocols. It is perhaps most natural when the conformance can be synthesized, - in my personal usage it's certainly conformance to Equatable
and Hashable
that I've wanted to confer on my tuple typed keys.
While it presumably is quite common to want to use something like (Int, Int)
as a key in your dictionary, I think that allowing (Int, Int)
to implement Hashable
is the wrong way to go - it goes against the whole purpose of tuple types, who are by definition anonymous.
An alternative approach, which removes this particular class of inconvenience, would be to allow struct and class types to be initialised/assigned to with tuple literals:
struct Coordinate: Hashable, ExpressibleByTupleLiteral {
let x: Int
let y: Int
}
would let you
let location: Coordinate = (5, 6)
let x = 5
let y = 6
let otherLocation: Coordinate = (x, y)
var locatedStrings: [Coordinate: String] = [:]
locatedStrings[location] = "clarity"
locatedStrings[(6, 7)] = "convenience"
and perhaps even:
let locationsAreEqual = Coordinate(x: 5, y: 6) == (x, y) // true
This would keep the convenience and clarity of the tuple literal, without compromising the tuple type's anonymous and simple nature.