Home > Software engineering >  Is it possible to declare a protocol with an associatedtype inside a protocol?
Is it possible to declare a protocol with an associatedtype inside a protocol?

Time:11-19

I want to declare a protocol with an associatedtype inside the protocol.

I know that declaring it as a class rather than a protocol solves the problem.

But I want to use it within the protocol.

Is there a way to use a protocol with an associated type in the protocol using things like generics or typealias?

protocol A {
    associatedtype T
}

protocol B {
    var a: A { get } // error. protocol 'A' can only be used as a generic constraint because it has Self or associated type requirements
                     // But I want set a.T = Int
}

CodePudding user response:

If you really want to set A.T to Int, you can specify that in an associated type where clause within B:

protocol A {
    associatedtype T
}

protocol B {
    associatedtype U: A where U.T == Int 
    var a: U { get }
}

Or, you do not want to lock B to only one particular A.T type, you can introduce another associatedtype, which links back to A:

protocol A {
    associatedtype T
}

protocol B {
    associatedtype T
    associatedtype U: A where U.T == T 
    var a: U { get }
}

See Associated Types with a Generic Where Clause in The Swift Programming Language.

CodePudding user response:

protocol A {
    associatedtype T
    var a: T { get }
}

protocol B {
    associatedtype U where U: A
    var b: U { get }
}

Keep in mind though that you're gonna have to reason a lot about this because of the two associated types.

  • Related