【问题标题】:How to define a protocol that specializes a generic protocol, so that it can be used in type declarations?如何定义专门化泛型协议的协议,以便可以在类型声明中使用?
【发布时间】:2020-06-04 16:51:17
【问题描述】:

我是一名学习 iOS 开发的 Android 开发人员,我遇到了这个使用 Kotlin/Java 接口微不足道的问题,但我无法使用 Swift 协议解决它。

假设我们有这个协议:

protocol ValueStore {
  associatedtype Value
  var value: Value? { get set }
}

在 Kotlin/Java 中,如果我想使用泛型抽象来定义变量类型,我只是使用带有类型参数的泛型接口:

val stringStore: ValueStore<String>

由于这在 Swift 中是不可能的,所以我尝试创建一个专门的子协议来定义关联类型:

protocol StringStore: ValueStore where Value == String { }

打算像这样使用后者:

let stringStore: StringStore

上面的声明是我想要实现的。然而编译器告诉我Protocol 'StringStore' can only be used as a generic constraint because it has Self or associated type requirements

虽然在类型声明中我可以使用专门的通用具体实现,即UserDefaultsValueStore&lt;String&gt;,但这违反了依赖倒置原则。

是否可以专门化具有关联类型的协议并仍然保持抽象级别?

【问题讨论】:

    标签: swift swift-protocols


    【解决方案1】:

    如果我正确理解了这个问题...试试这个:

    protocol ValueStoreType {
      associatedtype Value
      var value: Value? { get set }
    }
    
    struct ValueStore<T>: ValueStoreType {
      var value: T?
    }
    

    那么你就可以做到:

    var stringStore: ValueStore<String>
    

    【讨论】:

    • 这样我将声明一个具体的实现类型而不是抽象类型。它去掉了抽象层;这似乎又打破了 D.I.P.恐怕语言级别不支持我想要实现的概念,我想知道是否有解决方法。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-03
    相关资源
    最近更新 更多