以下代码无法编译:
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)
}
错误是:
cannot invoke 'decode' with an argument list of type '(C.Type, from: Data)'
let j = try JSONDecoder().decode(c, from: data)
声明c
变量以使其可以接收或键入A
或键入B
并仍然符合JSONDecoder().decode(...)
签名的正确方法是什么?