我正在尝试为我的类创建通用的公共接口。
我已经创建了接口
public protocol StorageProtocol {
associatedtype StorageObject: Codable
func store(storeObject: StorageObject)
func get() -> StorageObject?
}
和实现
public class Storage<T: Codable>: StorageProtocol {
public func store(storeObject: T) {}
public func get() -> T?
现在,当我尝试创建实例时它强制我任何关键字
let myStorage: any StorageProtocol = Storage<Credentials>()
和我不能调用storage.store(storeObject: Credentials())
,因为我得到错误:关联类型'StorageObject'只能与具体类型或泛型参数基一起使用。我错过了什么?
当您将myStorage
约束为any StoreageProtocol
时,编译器不知道在参数storeObject
中需要什么类型,因为通用的StorageObject
可以是任何Codable
对象。一种解决方法是显式地为泛型类型添加一个参数。
public protocol StorageProtocol<StorageObject> { // add a generic parameter
associatedtype StorageObject: Codable
func store(storeObject: StorageObject)
func get() -> StorageObject?
}
然后当你定义变量
时let myStorage: any StorageProtocol<Credentials> = Storage<Credentials>()
那么编译器将知道你想为这个变量存储Credentials
,并允许你在将协议专化为正确的类型时调用store
。