Home > Software engineering >  How do I make a protocol that my generic class can conform to?
How do I make a protocol that my generic class can conform to?

Time:10-08

I have a class along these lines:

class FooKeyValueStore<T: Codable> {
    func set(key: String, value: T) throws {
        // Do some stuff
    }
}

That I'd like to abstract behind a protocol. How can I define such a protocol please? I've tried the obvious approach of:

protocol KeyValueStore<Item> {
    associatedtype Item where Item == Codable
    
    func set(key: String, value: Item) throws
}

but the compiler complains that the class doesn't conform to the protocol.

Any help much appreciated! Thank you

CodePudding user response:

associatedtype Item where Item == Codable

This line is incorrect. You don't mean Item == Codable. You mean Item: Codable.

  • Related