I have an array of different structs, all implementing Equatable
protocol and am trying to pass it to a function that expects a collection where T.Iterator.Element: Equatable
. I know how to solve this problem by using classes and just creating a class Vehicle: Identifiable, Equatable
, and then make Car
and Tractor
implement Vehicle
. However I'd like to know if this is possible with using structs and protocols?
Here's a contrived example of what I'm trying to do
//: Playground - noun: a place where people can play
protocol Identifiable {
var ID: String { get set }
init(ID: String)
init()
}
extension Identifiable {
init(ID: String) {
self.init()
self.ID = ID
}
}
typealias Vehicle = Identifiable & Equatable
struct Car: Vehicle {
var ID: String
init() {
ID = ""
}
public static func ==(lhs: Car, rhs: Car) -> Bool {
return lhs.ID == rhs.ID
}
}
struct Tractor: Vehicle {
var ID: String
init() {
ID = ""
}
public static func ==(lhs: Tractor, rhs: Tractor) -> Bool {
return lhs.ID == rhs.ID
}
}
class Operator {
func operationOnCollectionOfEquatables<T: Collection>(array: T) where T.Iterator.Element: Equatable {
}
}
var array = [Vehicle]() //Protocol 'Equatable' can only be used as a generic constraint because Self or associated type requirements
array.append(Car(ID:"VW"))
array.append(Car(ID:"Porsche"))
array.append(Tractor(ID:"John Deere"))
array.append(Tractor(ID:"Steyr"))
var op = Operator()
op.operationOnCollectionOfEquatables(array: array) //Generic parameter 'T' could not be inferred