Okay ! I already added a workaround by implementing the method in BuildingTemplate2
, but since it has more than one property, It is a lot of code just for this...
struct BuildingTemplate: Encodable {
let name: String
let description: String
let maxLife: Double
let characteristics: [Characteristic: Double]
let requiredToBuild: [Resource: Int]
let skillsIds: [SkillId]
}
extension BuildingTemplate: Template {
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: BuildingTemplate.CodingKeys.self)
self.name = try container.decode(String.self, forKey: .name)
self.description = try container.decode(String.self, forKey: .description)
self.maxLife = try container.decode(Double.self, forKey: .maxLife)
let characteristicsDictionary = try container.decode([String: Double].self, forKey: .characteristics)
self.characteristics = try characteristicsDictionary.map { tuple in
guard let key = Characteristic(rawValue: tuple.key) else {
throw DecodingError.valueNotFound(
Characteristic.self,
DecodingError.Context(codingPath: [BuildingTemplate.CodingKeys.characteristics], debugDescription: "unable to build an enum value with value provided : \(tuple.key)")
)
}
return (key, tuple.value)
}
let requiredToBuildDictionary = try container.decode([String: Int].self, forKey: .requiredToBuild)
self.requiredToBuild = try requiredToBuildDictionary.map { tuple in
guard let key = Resource(rawValue: tuple.key) else {
throw DecodingError.valueNotFound(
Resource.self,
DecodingError.Context(codingPath: [BuildingTemplate.CodingKeys.requiredToBuild], debugDescription: "unable to build an enum value with value provided : \(tuple.key)")
)
}
return (key, tuple.value)
}
self.skillsIds = try container.decode([SkillId].self, forKey: .skillsIds)
}
}