如果在运行时将已知的具体类型存储在'Decodable.Type'变量中,如何解码该具体类型?

问题描述 投票:1回答:1

有点被类中最好的插图所困扰...

class AnyDecodableWrapper : Decodable {

    static let decodableTypesLookup:[String:Decodable.Type] = [ <-- 'Decodable.Type' here is what's causing the problem
        "str": String.self,
        "int": Int.self,
        "foo": Foo.self
    ]

    enum CodingKeys : String, CodingKey {
        case typeKey
        case value
    }

    required init(from decoder: Decoder) throws {

        // Get the container for the CodingKeys
        let container = try decoder.container(keyedBy: CodingKeys.self)

        // Get the key to look up the concrete type
        typeKey = try container.decode(String.self, forKey:.typeKey)

        // Attempt to get the concrete type from the key
        guard let concreteType = AnyDecodableWrapper.decodableTypesLookup[typeKey] else {
            value = nil
            return
        }

        // Attempt to decode an instance of the concrete type
        let concreteObject = try container.decode(concreteType, forKey: .value)

        value = concreteObject
    }

    let typeKey : String
    let value   : Any?
}

问题是分配温度concreteObject的行抱怨以下内容...

对成员'decode(_:forKey :)'的模糊引用

这当然是因为从字典返回的类型是Decodable.Type,而不是'String.self'之类的东西,因此不确定使用哪个decode重载。

因此,如果您将具体类型存储在Any.Type变量中,如何将其传递给正确的解码过载?

json swift codable
1个回答
0
投票
© www.soinside.com 2019 - 2024. All rights reserved.