Home > Software engineering >  Codable class doesn't conform to protocol 'Decodable'
Codable class doesn't conform to protocol 'Decodable'

Time:02-10

Try to add enum Codingkeys inside struct, But it show error Codable doesn't conform Decodable.

Why am i getting conform decodable error? Should i seperate the struct ?

struct Model: Codable {
    let aps: Aps
    let link: String?
    let checkAction: String?
   
    enum CodingKeys: String, CodingKey {
           case aps ,link, alert,sound,title,body
           case checkAction = "gcm.notificaiton.check_action"
    }
    
    struct Aps: Codable {
        let alert: Alert
        let sound: String?
       
        
        struct Alert: Codable {
            let title: String?
            let body: String?
        }
    }
   

}

Is it a must to seperate the struct like below ?

struct FCMModel: Codable {
    let aps: Aps
    let link: String?
    let checkAction: String?
   
    enum CodingKeys: String, CodingKey {
           case aps ,link
           case checkAction = "gcm.notificaiton.check_action"
    }
    

}
struct Aps: Codable {
    let alert: Alert
    let sound: String?
   
    
    struct Alert: Codable {
        let title: String?
        let body: String?
    }
}

CodePudding user response:

It is not necessary to separate the structs. The error occurs because you have added too many keys in the CodingKeys enum. If you keep only the required ones, then it will work:

struct Model: Codable {
    let aps: Aps
    let link: String?
    let checkAction: String?
   
    enum CodingKeys: String, CodingKey {
           case aps ,link
           case checkAction = "gcm.notificaiton.check_action"
    }
    
    struct Aps: Codable {
        let alert: Alert
        let sound: String?
       
        
        struct Alert: Codable {
            let title: String?
            let body: String?
        }
    }
}

alert, sound etc are not coding keys of Model. They are coding keys of Aps. It is not necessary to specify them in Aps, because they are the same as the property names.

  • Related