Search code examples
swiftswift-protocolsassociated-types

swift how to determine associatedtype in sub protocol


I have a question about protocol associatedtype.

Here is code..

protocol TestProtocol {
    associatedtype T: Equatable
}

struct Test {
    let value: TestProtocol
}

It has a error.

struct Test<T: TestProtocol> {
    let value: T
}

And It is ok. but i do not want to use generic in struct.

so I tried..

protocol IntTestProtocol: TestProtocol where T == Int  {

}

struct Test {
    let value: IntTestProtocol
}

But, this code also has error.

how can i determine TestProtocol's associatedtype in sub protocol? is it possible?


Solution

  • How about

    protocol TestProtocol {
        associatedtype T: Equatable
    }
    
    struct TestProtocolContainer<U: Equatable>: TestProtocol {
        typealias T = U
    }
    
    
    struct Test {
        let value: TestProtocolContainer<Int>
    }
    

    When you declare a protocol with associatedtype (which offers static polymorphism, If you are interested in understanding various types of polymorphism and how to achieve it with protocol in swift do give a read to my blogpost here).

    you cant use that protocol as Concrete type because compiler can't resolve the type of T during compilation. (Why during compilation, I said its static polymorphism remember :) )

    So that's why compiler expects you to provide it someway to help it resolve the type of associatedtype during compilation. One way is by providing typealias and specifying the actual data type of associatedtype.

    example :

    struct TestProtocolContainer: TestProtocol {
        typealias T = Int
    }
    

    This works great but then, you would want to make this Generic struct to represent any struct with Equatable type. Thats where Generics comes into picture.

    struct TestProtocolContainer<U: Equatable>: TestProtocol {
    

    This represents a Generic structure which uses any Equatable type and confirms TestProtocol and finally setting

    typealias T = U
    

    Ensures confirmation to TestProtocol

    Hope this helps