简体   繁体   中英

Codable class doesn't conform to protocol 'Decodable'

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM