[英]Decoding manually a non Codable property of a Codable class
ClassA 符合 Cadable 並具有一堆屬性。 其中之一是不符合 Codable 的已經存在的非常復雜的 ClassB 的屬性。 我可以手動解碼 Codable 類的非 Codable 屬性嗎?
struct ClassA: Codable {
let title: String?
let subtitle: String?
let property: ClassB?
enum CodingKeys: String, CodingKey {
case title
case subtitle
case property
}
required init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
title = try container.decode(String.self, forKey: .title)
subtitle = try container.decode(String.self, forKey: .subtitle)
let JSONString = ?
property = ClassB.initWith(JSONString: JSONString)
}
class ClassB: NSObject {
// Already existing very complex ClassB implemenatation...
}
我得到錯誤:
類型 'ClassA' 不符合協議 'Encodable'
是的你可以。
錯誤是您缺少func encode(to encoder: Encoder) throws
in ClassA
。 Codable = Encodable & Decodable
,因此它也試圖找到一種對ClassA
進行編碼的方法。 ClassB
不可編碼,因此它不能自動執行,而且您也沒有告訴它如何手動執行。
如果您不需要對ClassA
實例進行編碼,只需將其Decodable
。 否則實現缺少的encode
功能。
或者只是投入工作並使ClassB
編碼。 您可以使用擴展名在事后添加它。 如果您也不想這樣做,我使用的一種解決方法是在ClassA
聲明一個小的私有可編碼結構,如struct ClassBInfo: Codable
。 使用它來獲取您需要的信息,然后讀取其屬性以初始化ClassB
。
嘗試這個
struct ClassA: Codable {
let title: String?
let subtitle: String?
let property: ClassB?
enum CodingKeys: String, CodingKey {
case title
case subtitle
case property
}
required init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
title = try container.decode(String.self, forKey: .title)
subtitle = try container.decode(String.self, forKey: .subtitle)
let JSONString = ?
property = ClassB.initWith(JSONString: JSONString)
}
class ClassB: Codable {
// Already existing very complex ClassB implemenatation...
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.