【发布时间】: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<String>,但这违反了依赖倒置原则。
是否可以专门化具有关联类型的协议并仍然保持抽象级别?
【问题讨论】:
标签: swift swift-protocols