I wish to create a class which will store a Date and any object that conforms to the Codable protocol. I would like this class to also conform to the Codable protocol itself.
I can do this for one object as follows:
class CodableContainerA: NSObject, Codable {
var date: Date?
var item: CodableTypeA?
}
I'd rather not have to create a separate CodableContainerX for each CodableTypeX I have.
My current workaround is to create a class called CodableBaseClass that conforms to Codable, derive every CodableType from it and define my class as follows:
class CodableContainer: NSObject, Codable {
var date: Date?
var item: CodableBaseClass?
}
This seems a long way around and feels like something I should be able to do by making the CodableTypes conform to a protocol, but I'm not sure how. If I define item to be of type Codable? or (Any & Codable)? I get an error stating
Type 'CodableContainer' does not conform to protocol 'Decodable'
I'm using Swift 4.
Any help or advice would be gratefully accepted. Many thanks,