Can the value of a associatedtype be a protocol?
protocol A {
var name: String {get set}
}
protocol B: A {}
protocol C {
associatedtype T: B
var t : T {get set}
}
class D : C {
var t : B
init(t : B) {
self.t = t
}
}
class E : B {
var name: String = ""
}
class F : B {
var name: String = "ff"
}
In class D, if the type of t is E or F, the code compiles. But if the type of t is B(which is a protocol), compilation fails stating:
Type 'D' does not conform to protocol 'C'
How can I have an associated type to hold a protocol value? Any pointers to why it is failing?
Updated question
Removing bound on associatedtype and having just T will not help. My protocol also has methods on it which I want to access. For example:
protocol A {
func sayHello()
}
protocol B : A {
var name: String {get set}
}
extension B {
func sayHello() {
print("Hello")
}
}
protocol C {
associatedtype T
var t: T {get set}
}
class D : C {
typealias T = E
var t: T
init(t : T) {
self.t = t
}
}
class E : B {
var name: String = ""
}
class F : B {
var name: String = "ff"
}
class G<S: C> {
var a: S
init(a: S) {
self.a = a
}
func notWorking() {
a.t.sayHello()
}
}
In the above example, I am not able to access sayHello method.