Trying to convert from Swift 3 to Swift 4 in Xcode Version 9.0 beta 5 (9M202q)
I have a lot of NSCoding classes at the moment. Many have classes have members known only by protocol. Not a problem for NSCoding. However, I cannot find a way to encode/decode these members by protocol.
Can such data items that are only known by protocol be encoded and decoded? Or must I stick with NSCoding for now?
A short example, below. The line trying to encode someData, whose type is unknown but is known to be SomeProtocol, gets an error complaining that it cannot be invoked with the given arglist. The line trying to decode someData gives an error: No 'decode' candidates produce the expected contextual result type 'SomeProtocol'
protocol SomeProtocol: Codable {
var someData: Int { get }
}
class SomeClass: SomeProtocol {
let someData: Int = 9999
}
class SomeMore: Codable {
var someData: SomeProtocol = SomeClass()
required init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
someData = try container.decode(SomeProtocol.self, forKey: CodingKeys.someData)
}
func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
container.encode(someData, forKey: CodingKeys.someData)
}
enum CodingKeys: CodingKey {
case someData
}
}