在Swift 4中,使用Decodable
协议,当仅在运行时才知道要解码的类型时,是否有可能解码JSON对象?
我有一个类似注册表的东西,它将String
标识符映射到我们想要解码的类型,如下所示:
import Foundation
struct Person: Decodable {
let forename: String
let surname: String
}
struct Company: Decodable {
let officeCount: Int
let people: [Person]
}
let registry: [String:Decodable.Type] = [
"Person": Person.self,
"Company": Company.self
]
let exampleJSON = """
{
"forename": "Bob",
"surname": "Jones"
}
""".data(using: .utf8)!
let t = registry["Person"]!
try! JSONDecoder().decode(t, from: exampleJSON) // doesn't work :-(
我这样做对吗,还是有更好的方法?
Person.self
而不是 t。 - Leo Dabus