I was dealing with a request that need to modify our app config structure, the modification was moving the EncodingOption
parameter to the EditingOptions
class from OutputOptions
struct.
Hierarchy of the config
AppConfig {
profile: ProfileSetting
}
ProfileSetting {
editSetting:EditingOptions
outputSetting: OutputOptions
}
Previous data structure:
class EditingOptions: NSObject, Codable {
//..other parameters
}
struct OutputOptions: Codable {
var barcodeEncoding: EncodingOption = .utf8
//..other parameters
}
Modified data structure:
class EditSetting: NSObject, Codable {
var encodingOption: EncodingOption
//..other parameters
}
struct OutputSetting: Codable {
//..other parameters
}
The modified structure was not compatible with previous config file with the JSON error keyNotFound
:
keyNotFound(CodingKeys(stringValue: "encodingOption", intValue: nil),
Swift.DecodingError.Context(codingPath: [
CodingKeys(stringValue: "profileManage", intValue: nil), CodingKeys(stringValue: "deviceName",
intValue: nil), CodingKeys(stringValue: "profiles", intValue: nil),
_JSONKey(stringValue: "Index 0", intValue: 0),
CodingKeys(stringValue: "outputOptions", intValue: nil)
],
debugDescription: "No value associated with key CodingKeys(stringValue: "encodingOption", intValue: nil) ("encodingOption").", underlyingError: nil))
The solution from ChatGPT was add a init(from decoder: Decoder)
method for ProfileSetting
class:
required init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
//...other parameters
if let editingOptions = try? container.decode(EditingOptions.self, forKey: .editingOptions) {
self.editingOptions = editingOptions
} else {
self.editingOptions = EditingOptions()
}
}
The solution did resolved the keyNotFound
error, however, I’m not sured that the solution was the RIGHT way to solve the issue.