Swift动态类型调用,如何?

时间:2018-09-12 16:06:29

标签: swift swift4

以下代码无法编译:

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(...)签名的正确方法是什么?

0 个答案:

没有答案