【问题标题】:Protocol with associated type as type workarounds具有关联类型的协议作为类型解决方法
【发布时间】:2020-11-22 10:38:33
【问题描述】:

我知道目前不可能使用具有关联类型的协议作为类型。您能否帮助解决这种情况:

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]

我需要一个字典,其中键是字符串,值是符合“ProvidesResult”的类型。我需要它来使用provideResult 方法启动ResultProvider 的新实例。

【问题讨论】:

  • 如果要混合类型,则需要声明字典 [String: Any] 或将其声明为 ResultType 的类型,即 [String: Int]
  • 你需要一个类型橡皮擦,例如AnyProviderResult

标签: swift protocols associated-types


【解决方案1】:

一种方法是使用类型橡皮擦:

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)
    }
}

然后您可以在字典中使用上述结构:

var resultProviders: [String: AnyProvidesResult<TypeOfResult>]

这里的限制是字典中的值必须是同一类型,所以要么需要设置显式类型,要么使用公分母协议。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多