Swift 4. I have a very similar situation than Using Codable for a dynamic type / object , but for me a variable is the name of the dictionary and not inside. It looks like this:
{
"customName": {
"constantKey": Double,
"constantKey2": Double,
}
}
Here is the code I am trying to modify, it was suggested as an answer for another question, and I made small changes:
struct GenericCodingKeys: CodingKey {
var intValue: Int?
var stringValue: String
init?(intValue: Int) { self.intValue = intValue; self.stringValue = "\(intValue)" }
init?(stringValue: String) { self.stringValue = stringValue }
static func makeKey(name: String) -> GenericCodingKeys {
return GenericCodingKeys(stringValue: name)!
}
}
struct MyModel: Decodable {
var customName: [String: Double]
private enum CodingKeys: String, CodingKey {
case customName
}
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
customName = [String: String]()
let subContainer = try container.nestedContainer(keyedBy: GenericCodingKeys.self, forKey: .customName)
for key in subContainer.allKeys {
customName[key.stringValue] = try subContainer.decode(Double.self, forKey: key)
}
}
}
And here is the obvious error I received as I don’t know how to change this user name: keyNotFound(Testapp.MyModel.(CodingKeys in _7A951077E4B6EF2E56D367C5DE0BF0AC).customName, Swift.DecodingError.Context(codingPath: [], debugDescription: "Cannot get KeyedDecodingContainer<GenericCodingKeys> -- no value found for key \"customName\"", underlyingError: nil))
source
share