Search code examples
jsonswiftcodableurlsession

ignore the following properties in swift Codable?


I have this Account struct. I want to ignore the following properties environments and Id in encoding to JSON object when I send "POST" endpoint and use them return success decoding to swift object

update I have this error Property type '[Environment]' does not match that of the 'wrappedValue' property of its wrapper type 'SkipEncode'

struct Account: Codable {
    let accountID, displayName, managedByID, id: String
    let environments: [Environment]
    let contacts: [Contact]

    enum CodingKeys: String, CodingKey {
        case accountID
        case displayName
        case managedID
        case id
        case environments
        case contacts
    }
}

Solution

  • If you want to ignore, for example environments when encoding, you can define your own encoding implementation:

    struct Account: Codable {
        let accountID, displayName, managedByID, id: String
        let environments: [Environment]
        let contacts: [Contact]
    
        enum CodingKeys: String, CodingKey {
            case accountID, displayName, managedByID, id, environments, contacts
        }
    
        func encode(to encoder: Encoder) throws {
            var container = encoder.container(keyedBy: CodingKeys.self)
            try container.encode(accountID, forKey: .accountID)
            try container.encode(displayName, forKey: .displayName)
            // ... just don't include the environments here
        }
    }