Value of protocol type 'Encodable' cannot conform to 'Encodable'; only struct/enum/class types can conform to protocols
Encodable
cannot be used as an annotated type. It can be only used as a generic constraint. And JSONEncoder
can encode only concrete types.
The function
func doStuff<T: Encodable>(payload: [String: T]) {
is correct but you cannot call the function with [String: Encodable]
because a protocol cannot conform to itself. That's exactly what the error message says.
The main problem is that the real type of things
is [String:Any]
and Any
cannot be encoded.
You have to serialize things
with JSONSerialization
or create a helper struct.
You're trying to conform T
to Encodable
which is not possible if T == Encodable
. A protocol does not conform to itself.
Instead you can try:
func doStuff<T: Hashable>(with items: [T: Encodable]) {
...
}