The following code doesn't compile:
import Foundation
import PlaygroundSupport
protocol C : Decodable {
}
class A : C {
let code: Int
}
class B : C {
let blob: Int
}
var c : C.Type
let a = A.self
let b = B.self
let i = 100
if i == 100 {
c = a
}
else if i < 100 {
c = b
}
do {
let data = String("{\"code\": 123}").data(using: .utf8)!
let j = try JSONDecoder().decode(c, from: data)
print(j)
}
catch let error as NSError{
print(error.debugDescription)
}
The error is:
cannot invoke 'decode' with an argument list of type '(C.Type, from: Data)'
let j = try JSONDecoder().decode(c, from: data)
What would be the proper way to declare the c
variable so it could receive or type A
or type B
and still complies with JSONDecoder().decode(...)
signature?