Constraining associated type(s) of opaque types

Hello!

I was trying to use an opaque type

func combinations<S1: Sequence, S2: Sequence>(_ sequence1: S1, 
                                              _ sequence2: S2)  ->  some Sequence {
    sequence1.lazy.flatMap { element1 in
      sequence2.lazy.map { element2 in
        (element1, element2)
      }
    }
}

While this compiles it is not very useful at the call site because I can't iterate over the tuple. The workaround is to go back to a AnySequence<(S1.Element, S2.Element)> return type.

The documentation talks about inferring the associated type, but it doesn't let me here. It seems like it should be possible to constrain the associated type of the opaque type with the same basic language feature. I would be really nice to be able to say,

some Sequence where Element = (S1.Element, S2.Element)

Anyway, I am wondering if there is any plans to improve the situation or if there was a fundamental reason that makes this hard to do.

1 Like

It is a natural extension of the feature that just hasn't been implemented at this point.

Thanks for the info. Very glad to hear that. :smile:

If you don't mind asking, it seems like from the documentation https://docs.swift.org/swift-book/LanguageGuide/OpaqueTypes.html (see the end) that some associated values should be inferred.

Is there some reason why it cannot infer the tuple of associated types? I am just wondering if this is a bug / implementation limitation or something that actually needs to be pitched?

I searched a little bit on bugs.swift.org but didn't see anything reported along these lines.

Edit: My question is in the fullness of time if this will need a constraint annotation or will be automatically inferred.

The documentation is unclear/misleading: type(of:) gives the dynamic type and doesn't tell you what the static type is. The point of an opaque type is that the underlying type is--as the name suggests--opaque so far as the static type is concerned. I'd file a bug against the documentation.

In the fullness of time, you'll need to write a constraint, or else that will be opaque to the user of your API.

Gotcha. My assessment of type(of:) was in error (from another post). I tried to edit it, but I guess it wasn't fast enough. Thank you. Considering it from the API user's perspective is a great way to think about the feature.

Terms of Service

Privacy Policy

Cookie Policy