簡體   English   中英

Codable class 不符合“可解碼”協議

[英]Codable class doesn't conform to protocol 'Decodable'

嘗試在結構中添加枚舉 Codingkeys,但它顯示錯誤 Codable doesn't conform Decodable。

為什么我會收到一致的可解碼錯誤? 我應該分開結構嗎?

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

}

是否必須像下面這樣分離結構?

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

沒有必要分離結構。 發生錯誤是因為您在CodingKeys枚舉中添加了太多鍵。 如果您只保留所需的,那么它將起作用:

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

alertsound等不是Model的編碼鍵。 它們是Aps的編碼鍵。 不必在Aps中指定它們,因為它們與屬性名稱相同。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM