I have been thinking about a way to use a Protocol type as a dictionary key. I made a simple test code in the playground:
//Custom Protocol conforms to Hashable
protocol Transport: Hashable {
var name: String {get set}
var quantity: Int {get set}
}
//Transport Protocol extension
extension Transport {
var hashValue: Int {
return name.hashValue ^ quantity.hashValue
}
}
//Equatable Protocol (Since Hashable conforms to Equatable)
func ==<T:Transport>(lhs: T, rhs: T) -> Bool {
return lhs.hashValue == rhs.hashValue
}
//Struct Car
struct Car: Transport {
var name: String = ""
var quantity: Int = 1
init(name: String, quantity: Int) {
self.name = name
self.quantity = quantity
}
}
//Struct Plane
struct Plane: Transport {
var name: String = ""
var quantity: Int = 1
init(name: String, quantity: Int) {
self.name = name
self.quantity = quantity
}
}
let t1 = Car(name: "Ford", quantity: 10)
let t2 = Plane(name: "Airbus", quantity: 2)
Next line gives an error: Binary operator '==' cannot be applied to operands of type 'Car' and 'Plane'
if t1 == t2 {
print("It's the same transport")
}
Next line gives this error: Using 'Transport' as a concrete type conforming to protocol 'Hashable' is not supported
var arrayOfTransports = [Transport:[Int]]()
What I am trying to do is to compare structures that conform to 'Transport' Protocol, and be able to use these structs as Dictionary keys.