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.
Generic Protocols with Associated Type
protocol C {
associatedtype T
var t : T {get set}
}
anything that conforms to C must implement associatedtype T . However, the type is not defined. Therefore, the class or struct that conforms to the protocol must define it either implicitly or explicitly.
First, let’s create a class SomeClass that conforms to C. We must define t. Well, You may define t based on the value associated with T.
class D : C {
typealias T = B
var t: B
init(t : B) {
self.t = t
}
}
Update
You have created T associatedtype, means assign a dynamically generic type value, in this case, T value is already assigned. why are you creating an associatedtype, you can use directly. like
protocol C {
//associatedtype T: B
//var t : T {get set}
var t: B {get set} // write directly.
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With