Protocol with associated type as type workarounds

81 Views Asked by At

I know that currently it isn't possible to use protocols with associated types as types. Could you please help with workarounds for this case:

protocol ProvidesResult {
    associatedtype ResultType

    func provideResult(input: String) -> ResultType
}

class IntProvider: ProvidesResult {
    typealias ResultType = Int
    
    func provideResult(input: String) -> ResultType {
        //Logic
    }
}

var resultProviders: [String: ProvidesResult]

I need a dict where key is string and value is type that conforms to "ProvidesResult". I need it to initiate new instances of ResultProvider with provideResult method.

1

There are 1 best solutions below

0
On

One approach is to use a type eraser:

struct AnyProvidesResult<T>: ProvidesResult {

    private _provideResult: (String) -> T

    init<PR>(_ pr: ProvidesResult) where PR: ProvidesResult {
        _provideResult = pr.provideResult
    }

    func provideResult(input: String) -> T {
        return _provideResult(input)
    }
}

You can then use the above construct within your dictionary:

var resultProviders: [String: AnyProvidesResult<TypeOfResult>]

The restriction here is that the values in the dictionary need to be of the same type, so you either need to set an explicit type, or use a common denominator protocol.