如何定义专门用于通用协议的协议,以便可以在类型声明中使用它?

问题描述 投票:1回答:1

[我是一名学习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
1个回答
0
投票

如果我正确理解了问题,请尝试以下操作:

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

struct ValueStore<T>: ValueStoreType {
  var value: T?
}

然后您将可以执行:

var stringStore: ValueStore<String>
© www.soinside.com 2019 - 2024. All rights reserved.