3

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.

Adeline
  • 465
  • 5
  • 16

1 Answers1

1

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]()
}
Dávid Pásztor
  • 51,403
  • 9
  • 85
  • 116
  • 1
    That's so good... thx. What's the difference between declaring `class SourceListHeader:Codable` and using `var children: [Item] = [Item]()` and declaring `class SourceListHeader:Codable` and using `var children: [SourceListItem] = [SourceListItem]()`. To me it looks like `` only tells the compiler that Item conforms to `SourceListItem`... which is the same as `var children: [SourceListItem]` – Adeline Jun 25 '19 at 16:45
  • 1
    `Item` is a concrete type conforming to `Codable`, while `SourceListItem` is a protocol inheriting from `Codable`. However, [Protocols don't conform to themselves](https://stackoverflow.com/questions/33112559/protocol-doesnt-conform-to-itself), hence the need for generics. – Dávid Pásztor Jun 25 '19 at 17:04