Conditional conformances for protocols?

Hi everybody,

Given this very simple example:

protocol Fragment: Codable {}

struct NaviState: Codable { <-- Type 'NaviState' does not conform to protocol 'Decodable'
    var path: [Fragment] 
}

Common sense says it should conform to the Codable protocol, since we have a protocol that guarantees conformance (Fragment) and only one single field, (path) which is an array codable as long as it has codable elements.

Still, the compiler doesn’t agree. Can someone help me understand why?

Codable requires concrete types. With your current design, how would the decoder know which type to decode the fragments into?

init(from decoder: Decoder) throws {
    var container = try decoder.container(keyedBy: CodingKeys.self)
    path = try container.decode(/* what? */, forKey: .path)
}
3 Likes

Absolutely. You’re right, my logic holds only for getting the opaque value, but there’s no way to know the type. Thanks Tomáš

1 Like