3

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.

Sajani
  • 117
  • 8
  • 1
    [Protocols don't always conform to themselves](https://stackoverflow.com/a/43408193/2976878) – `B` is not a type that conforms to `B`, so cannot satisfy the associated type `associatedtype T: B`. – Hamish Apr 12 '18 at 10:09

1 Answers1

1

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.
}
AshvinGudaliya
  • 3,234
  • 19
  • 37
  • In the above implementation, basically we are removing the upper bound while defining the associatedType. But this means that we can not access any methods that are defined inside the protocol. – Sajani Apr 12 '18 at 14:49
  • @Sajani check out my updated answer – AshvinGudaliya Apr 12 '18 at 15:57