0

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?

Gobe
  • 2,559
  • 1
  • 25
  • 24
  • 1
    You're completely right – there's no real reason why it shouldn't be valid. Swift just doesn't support it yet. See [Why can't a get-only property requirement in a protocol be satisfied by a property which conforms?](http://stackoverflow.com/q/42561685/2976878). – Hamish Mar 10 '17 at 08:38
  • thank you @Hamish, unfortunately I hadn't found that other question, nor did stack overflow suggest me as a possible duplicate. – Gobe Mar 10 '17 at 13:14

0 Answers0