-2

I have the following structure to decode JSON data:

UPDATED:

struct Section {
    let owner : String
    var items : [ValueVariables]
}

struct ValueVariables : Decodable {
    var isSelected = false
    let breed: String
    let color: String
    let tagNum: Int

    // other members 
}

The issue is isSelected is not a value being decoded, how can I exclude it from being decoded to prevent it from causing an error like this:

keyNotFound(CodingKeys(stringValue: "isSelected", intValue: nil), Swift.DecodingError.Context(codingPath: [_JSONKey(stringValue: "Index 0", intValue: 0)], debugDescription: "No value associated with key CodingKeys(stringValue: \"isSelected\", intValue: nil) (\"isSelected\"), converted to is_selected.", underlyingError: nil))

I have tried using coding keys like this, but it does not seem to work :

private enum CodingKeys : String, CodingKey {
    case isSelected = "isSelected"
}

Applied Answer:

struct ValueVariables : Decodable {

    private enum CodingKeys : String, CodingKey {
        case breed, color, tagNum
    }

    var isSelected = false
    let breed: String
    let color: String
    let tagNum: Int
}

The JSON Looks like this:

[{"breed":"dog","color":"black","tagNum":20394}]

Error recieved:

Type 'ValueVariables' does not conform to protocol 'Decodable'

John
  • 965
  • 8
  • 16
  • isSelected is a computed var? Is it a var for UI? Then don't mix like that your "data model" and a ui-model. Is it an addon? – Larme Sep 16 '19 at 14:49
  • Your latest version of the posted code does _not_ generate an error. If your own code is different and generates an error you need to tell us but to me this question has been already correctly answered. – Joakim Danielson Sep 16 '19 at 15:39
  • Please see my update – John Sep 16 '19 at 16:11

1 Answers1

4

The other way round, you have to specify all keys which are going to be decoded.

struct ValueVariables : Decodable {

    private enum CodingKeys : String, CodingKey {
        case breed, color
    }

    var isSelected = false
    let breed: String
    let color: String
}
vadian
  • 274,689
  • 30
  • 353
  • 361