Suppose I have a generic class-bound protocol called Car that has an associated type which inherits from AnyObject. This protocol has a variable and an addPassenger() function defined and provides a default implementation for it.
I need the associated type to inherit from AnyObject because I want to be able to use === to filter out instances I already know about when calling addPassenger().
protocol Car: class {
associatedtype T: AnyObject
var passengers: [T] { get set }
func addPassenger(_ passenger: T)
}
extension Car {
func addPassenger(_ passenger: T) {
guard passengers.index(where: { $0 === passenger }) == nil else {
return
}
passengers.append(passenger)
}
}
I then have another protocol called Passenger which must be usable with Car:
protocol Passenger: AnyObject {}
Finally, suppose I have an instance of a class called SomeClass which conforms to the Car protocol and defines an array of Passengers:
class SomeClass: Car {
internal var passengers: [Passenger] = []
}
However, this is not possible because apparently Passenger does not conform to AnyObject:
error: type 'SomeClass' does not conform to protocol 'Car'
note: unable to infer associated type 'T' for protocol 'Car'
note: inferred type 'Passenger' (by matching requirement 'passengers') is invalid: does not conform to 'AnyObject'
Any idea what am I missing?