2

I have a Codable struct myObj:

public struct VIO: Codable {

    let id:Int?;
    ...
    var par1:Bool = false; //default to avoid error in parsing
    var par2:Bool = false;    
}

When I do receive JSON, I don't have par1 and par2 since these variables are optional. During parsing I get an error:keyNotFound(CodingKeys(stringValue: \"par1\", intValue: nil)

How to solve this?

1 Answer 1

3

If you have local variables you have to specify the CodingKeys

public struct VIO: Codable {

    private enum CodingKeys : String, CodingKey { case id }

    let id:Int?
    ...
    var par1:Bool = false
    var par2:Bool = false  

}

Edit:

If par1 and par2 should be also decoded optionally you have to write a custom initializer

  private enum CodingKeys : String, CodingKey { case id, par1, par2 }

   init(from decoder: Decoder) throws {
      let container = try decoder.container(keyedBy: CodingKeys.self)
      id = try container.decode(Int.self, forKey: .id)
      par1 = try container.decodeIfPresent(Bool.self, forKey: .par1)
      par2 = try container.decodeIfPresent(Bool.self, forKey: .par2)
  }

This is Swift: No trailing semicolons

Sign up to request clarification or add additional context in comments.

12 Comments

so in my case I need to simply include private enum CodingKeys : String, CodingKey { case par1 = false case par2 = false } ?
@AlexP No... what he showed is your case. The coding keys are usually inferred from the type's property names. Specifying the coding keys explicitly gives you a chance to omit par1, and par2, and just have id.
this means in CodingKeys I shall put all variables that I am sure are present in JSON?
You need to specify only the CodingKeys you want to decode.
I have a problem: now these values are never parsed even if present
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.