创建泛型类型的接口



我正在尝试为我的类创建通用的公共接口。

我已经创建了接口

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

最新更新