Paul
Paul

Reputation: 2047

How do I make a protocol that my generic class can conform to?

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

Upvotes: 0

Views: 49

Answers (1)

Rob Napier
Rob Napier

Reputation: 299265

associatedtype Item where Item == Codable

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

Upvotes: 2

Related Questions