Search code examples
swiftdecodable

Using Coding Keys to exclude values from being decoded


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'


Solution

  • 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
    }