1

I have a strange issue with swift generic protocol. Here is the example code I have:

protocol A {
    var s: String? { get }
}

protocol B: A {
    var d: Int? { get }
}

protocol Aed {
    associatedtype T: A

    var a: T! { get }
}

class AClass: Aed {
    var a: B!
}

And on line class AClass: Aed { I'm getting error type 'AClass' does not conform to protocol 'Aed'. I do not understand why swift unable to infer the type of a, it seems straightforward, no?

Ruben
  • 290
  • 3
  • 14

2 Answers2

1

The reason seems the same why you can't do this:

protocol A {
    var s: String? { get }
}

protocol B: A {
    var d: Int? { get }
}

class AClass<T: A> {
    var a: T!
}

class BClass: AClass<B> {
}

Here swift gives error using 'B' as a concrete type conforming to protocol 'A' is not supported. Swift do not support using protocol as a type for generic constraint. You need to provide concrete implementation.

Ruben
  • 290
  • 3
  • 14
  • For more on the topic, see https://stackoverflow.com/questions/33112559/protocol-doesnt-conform-to-itself/43408193#43408193. The underlying problem is that protocols do not conform to themselves (nor do they conform to their supertypes). You will need to find another approach. – Rob Napier Mar 28 '18 at 23:25
0
protocol A {
    var s: String? { get }
}

protocol B: A {
    var d: Int? { get }
}

protocol Aed {
    associatedtype T: A

    var a: T! { get }
}

class AClass<Element:B>: Aed {
    typealias T = Element

    var a: Element!

}


// usage
class MyElement: B {
    var d: Int?

    var s: String?
}

var myElement = MyElement()

myElement.d = 100

myElement.s = "hello"

var anInstance = AClass<MyElement>()

anInstance.a = myElement

print(anInstance.a.d ?? 0) // 100
print(anInstance.a.s ?? "") // hello
Gi0R
  • 1,387
  • 2
  • 13
  • 15
  • I came to this before, but It's not a good solution. At first it force me to have generic types were I can have final classes. Second I need to anyway specify type when creating instance, and that's not what I want. I want the type to be specified only during assignment, so I can make protocol public and implementation internal. And the last but not least if my type is ViewController, and I want to use it in interface builder, I can't make it generic. – Ruben Mar 28 '18 at 22:02