When creating a protocol that requires inheritance to a class that specialises a generic protocol
, the extension
implementation is lost outside of the protocol definition.
// Interface
protocol FooType: Hashable, CaseIterable { }
protocol BarType: Hashable { }
protocol Resolver {
associatedtype Foo: FooType
associatedtype Bar: BarType
func bar(for foo: Foo) -> Bar
}
protocol Provider {
associatedtype Foo: FooType
associatedtype Bar: BarType
typealias FooBarMap = [Foo: Bar]
var map: FooBarMap { get }
}
extension Provider {
subscript(_ foo: Foo) -> Bar? {
map[foo]
}
}
// Implementation
enum ActualFoo: FooType, CaseIterable {
case fooOne, fooTwo
}
enum ActualBar: BarType {
case barOne, barTwo
}
class BaseProvider: Provider {
typealias Foo = ActualFoo
typealias Bar = ActualBar
let map: FooBarMap
init(map: FooBarMap) {
self.map = map
}
}
let bp: BaseProvider?
bp?[.fooOne] // works fine, no compiler errors
protocol ExtraProvider: BaseProvider {
var firstBar: Bar? { get }
}
extension ExtraProvider {
func foo() {
self[.fooOne] // works fine, no compiler errors
}
}
var ep: ExtraProvider?
ep?[.fooOne] // Cannot infer contextual base in reference to member 'fooOne'
and the error I get is:
Again, I'm not sure if my assumptions that I make about the generics
are correct and this outcome is expected or the compiler is acting a bit funny.
Thank you!