Home > Software design >  Create interface with generic types
Create interface with generic types

Time:01-09

I'm trying to create public interface for my class operating on generics.

I've created interface

public protocol StorageProtocol {
    associatedtype StorageObject: Codable
    func store(storeObject: StorageObject)
    func get() -> StorageObject?
}

and implementation

public class Storage<T: Codable>: StorageProtocol {

    public func store(storeObject: T) {}
    public func get() -> T?

Now, when I try to create instance it forces me any keyword

let myStorage: any StorageProtocol = Storage<Credentials>()

and I can't call storage.store(storeObject: Credentials()) as I'm getting error: Associated type 'StorageObject' can only be used with a concrete type or generic parameter base. What I'm missing here?

CodePudding user response:

The compiler does not know what type to require in the parameter storeObject when you constrain myStorage to be any StoreageProtocol, as the generic StorageObject could be any Codable object. A workaround could be to explicitly add a parameter for the type of the generic.

public protocol StorageProtocol<StorageObject> { // add a generic parameter
    associatedtype StorageObject: Codable
    func store(storeObject: StorageObject)
    func get() -> StorageObject?
}

and then when you define the variable

let myStorage: any StorageProtocol<Credentials> = Storage<Credentials>()

Then the compiler will know you want to store Credentials for this variable and allow you to call store as you specialized the protocol to the correct type.

  • Related