protocol Builder {
associatedtype Output where Output: MyProtocol
func build() -> Output?
}
// concrete type
struct ABuilder: Builder {
func builder() -> MyProtocol {
if someCondition {
return aSubClassOfMyProtocol
} else {
return anotherSubClassOfMyProtocol
}
}
}
MyProtocol is a protocol type. It is also the Output constraint. Because the concrete Builder ABuilder is going to return two different sub class types that conform MyProtocol. How can I make the generic constraint work?
I am trying to make the generic constraint be the same.
You can make
build()function generic or use typecasting. Anyway this two ways determine concrete type outside of method not inside. So first of all you need to removeassociatedtype. If you specify associated typeOutputit means that the implementation of yourBuilderprotocol should return some concrete type which conforms toMyProtocol. If you want yourBuilderto return any type which conforms toMyProtocolnot the concrete one specified for this implementation of Builder then you shouldn't declare any associated types.Let's see how type casting can work:
Or we can use generic approach:
You can read more about that here, here and here. Moreover I strongly recommend watching this video which describes all the limitations of generics in swift.