Opaque Types and Closures

I'm trying to write a function that returns a some of a Protocol, so an Opaque Type. I would just use Protocol Existentials, but my protocol has associated type requirements.

So anyway, my problem is that I have another struct, whose initializer relies on a function builder that has the type () -> MyProtocol. Now when I use the function I described in the first paragraph within the function builder, I return some of MyProtocol. So I would need to change the closure type to () -> some MyProtocol. The issue is, that's not implemented.

I'm not sure how I could circumvent this. I may have to use type erasure to avoid returning an Opaque Type.

Hope this makes sense, I can add more detailed snippets if it's not enough info.

What about generics?

protocol MyProtocol { }

struct Builder<Product: MyProtocol> {
    let function: () -> Product
    init(function: @escaping () -> Product) {
        self.function = function
    func build() -> Product {

Or does your builder function return instances of different types?

1 Like