Making class codable

Viewed 70

I have a protocol, that is Codable and a class, that is Codable :

public protocol SourceListItem: AnyObject, Codable
{
    var name: String { get set }
    var children: [SourceListItem] { get set }
}

final public class SourceListHeader: Codable
{
    var name: String = "Give me a name!"
    var children: [SourceListItem] = [SourceListItem]()
}

However, the complier give me two errors :

Type 'SourceListHeader' does not conform to protocol 'Decodable'
Type 'SourceListHeader' does not conform to protocol 'Codable'

Why is that? I can't fix the error, and I have tried many variations...

The issue seems to come from the protocol, because if I remove it, everything works fine. It is like the compiler fails to see that the protocol only applies to Codable classes.

1 Answers

You need a concrete type conforming to Codable, you can't use a protocol conforming to Codable.

final public class SourceListHeader<Item: Codable>: Codable {
    var name: String = "Give me a name!"
    var children = [Item]()
}
Related