0

I have the following struct:

struct ImageSlider: CodableComponent {
    let slides: [CodableComponent]?
}

which conforms to CodableComponent

protocol Component {

}

typealias CodableComponent = Component & Decodable

But I get the following error:

Type 'ImageSlider' does not conform to protocol 'Decodable'

As soon as I remove the conformance to CodableComponent in ImageSlider, like the following:

struct ImageSlider {
    let slides: [CodableComponent]?
}

The error is gone.

I'm not sure what exactly is happening here, why I cannot conform to a protocol and also have a property of the same type?

Would be appreciated if someone could shed some light on this case.

Mina
  • 2,167
  • 2
  • 25
  • 32
  • 2
    You need to implement `init(from:)`, which is a requirement of `Decodable`. It doesn't get synthesised here because `Component & Decodable` is not `Decodable`. See https://stackoverflow.com/questions/33112559/protocol-doesnt-conform-to-itself – Sweeper May 03 '22 at 10:55
  • I'm guessing there are only a limited number of `CodableComponent`s that can be in `slides`? Check if you can decode each of them in `init(from:)`. – Sweeper May 03 '22 at 10:58
  • Thank Sweeper. The error is gone now. I also found another way to get around it, by using "existential any" in Swift 5.6. – Mina May 03 '22 at 12:05

2 Answers2

2

You have to implement Decodable protocol, for example:

struct ImageSlider: CodableComponent {
    let slides: [CodableComponent]?
    
    init(from decoder: Decoder) throws {
        // decode values here
    }
}
0

So, I found out that there are 2 ways to address this issue. The first one is using init(from:) as you can see in the comments and other answers. The other one is by using "existential any" in Swift 5.6

struct ImageSlider: any CodableComponent {
    let slides: [any CodableComponent]
}
Mina
  • 2,167
  • 2
  • 25
  • 32