Swift:如何让泛型类遵循自定义泛型协议?
正确定义协议的方案
你的问题出在协议关联类型的约束写法上,正确的协议定义应该把关联类型的Codable约束直接通过冒号声明,而不是用where Item == Codable的语法。下面是两种可行的写法:
方式一:使用主关联类型(Swift 5.7+)
protocol KeyValueStore<Item> { associatedtype Item: Codable func set(key: String, value: Item) throws }
此时让FooKeyValueStore遵循协议时,可以显式指定主关联类型,也可以让编译器自动推断:
// 显式指定关联类型 class FooKeyValueStore<T: Codable>: KeyValueStore<T> { func set(key: String, value: T) throws { // Do some stuff } } // 或让编译器自动推断(效果一致) class FooKeyValueStore<T: Codable>: KeyValueStore { func set(key: String, value: T) throws { // Do some stuff } }
方式二:不使用主关联类型(兼容更早Swift版本)
如果不需要主关联类型的语法,也可以这样定义协议:
protocol KeyValueStore { associatedtype Item: Codable func set(key: String, value: Item) throws }
对应的类遵循协议的代码和上面一致,编译器会自动将T推断为协议的Item关联类型。
错误原因说明
你之前的associatedtype Item where Item == Codable是错误的语法,where子句在这里用于关联类型和其他类型的关联约束(比如关联类型和协议自身或其他关联类型的关系),而直接约束关联类型遵循某个协议,应该使用associatedtype Item: Codable的形式。
内容的提问来源于stack exchange,提问作者Paul
相关产品推荐
相关产品推荐

