Cast AnyPublisher to Publisher in Combine

980 views Asked by At

I am using a Publisher<Int,Never> in combine, and I am trying to return a Published<Int>.Publisher

It is possible in combine to transform an AnyPublisher<Int,Never> into a Published<Int>.Publisher ?

1

There are 1 answers

0
Dávid Pásztor On

No, this is not possible. AnyPublisher is a type erased version of Publisher. Once you type erase a variable, the original type information is lost (or at the very least hidden) for the lifetime of the object, you cannot convert it back to the original type.

If you need to return a Published<Int>.Publisher, simply make that the return type of your function. Published<Int>.Publisher is a struct, so you can use it as a return type (unlike Publisher, which is a protocol with associated types).