As part of a rewrite from a C++ codebase, I have a class with an array of any V, where V extends Codable. How can I create the required init and encode functions here?
import Foundation
protocol V: Codable {
// some methods
}
// some other classes implementing V
class T: V {
var elements: [any V]
private enum CodingKeys: String, CodingKey {
case elements
}
required init(from decoder: Decoder) throws {
let container: KeyedDecodingContainer<T.CodingKeys>
= try decoder.container(keyedBy: CodingKeys.self)
self.elements = try container.decode([any V].self, forKey: .elements)
}
func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(elements, forKey: .elements)
}
}
Thanks in advance