Using opaque return types with protocols in Swift

40 Views Asked by At

I'm exploring a way to declare a specific type adhering to a protocol as a return type in a protocol in Swift 5.7, without exposing the details of the specific return type. Opaque types fit the bill, but unfortunately they cannot be used as return types in protocols unless they are declared as associated types, which is not my case. This becomes troublesome with Combine, for example:

protocol SomeProtocol {
    func doSomething() -> some Publisher<Bool, Never> // Error: Not allowed by language design
}

class SomeClass: SomeProtocol {
    func doSomething() -> some Publisher<Bool, Never> {
        Just(false)
    }
}

The return type is very specific to the implementation of the method and makes no sense as an associated type, especially if the number of methods grows and they perform different operations.

Is there any way to model this gracefully, without resorting to any Publisher<Bool, Never>, which expresses something slightly different?

I searched the depth of the internet to no avail and experimented with generics, but there doesn't seem to be a way to use versatile opaque return types with protocols currently.

0

There are 0 best solutions below