This limitation sounds very odd to me and I can't say if this should be considered a bug, a lacking feature or something that I should learn in order to agree that what Swift does is perfectly acceptable.
If I have a protocol requiring a type A somewhere, I can't implement this protocol using a type B that inherits from or implements A - unless I make my protocol generic. Generic protocols still have some limitations, so I'd like to use them only when I really need generics, i.e. when I want this protocol to handle multiple and unrelated types with type-safety.
Let's see some code - this won't compile:
protocol FooProtocol { }
struct ConcreteFoo: FooProtocol { }
protocol FooContainer {
var foo: FooProtocol? { get }
}
class Bar: FooContainer {
var foo: ConcreteFoo?
}
Swift says that Bar
does not conform to the FooContainer
protocol because it misses a foo: FooProtocol?
property. However, it doesn't really miss, because ConcreteFoo
is a/implements FooProtocol
so my foo
property should have been seen as a FooProtocol
. From what I know so far, that should be valid.
Now, introducing generics (unnecessarily?), this will obviously compile:
protocol FooProtocol { }
struct ConcreteFoo: FooProtocol { }
protocol FooContainer {
associatedtype AnyFoo: FooProtocol
var foo: AnyFoo? { get }
}
class Bar: FooContainer {
var foo: ConcreteFoo?
}
But as you know, with this code, I won't be able to have FooContainer
instances around without writing a separate, type-erased class.
So, from what I can tell, Swift 3 requires me to use generic protocols if I want conformance using subtypes. Why?