The simplest way to make a type codable is to declare its properties using types that are already Codable
. These types include standard library types like String
, Int
, and Double
; and Foundation types like Date
, Data
, and URL
. Any type whose properties are codable automatically conforms to Codable
just by declaring that conformance.
上面這段是從 Apple Developer Document 節取的,在 standard library types (String, Int, Double)以及 Foundation types (Date, Data, URL),這些類型已經被定義可編碼;若是自行定義的型別也想要可以編碼的話,就是去實作 Codable 協定。實作 Codable 協定的型別,可以使用方法 init(from:) 和 encode(to:)。
在自行建構的類別上實作 Codable 可將它們序列化為任何 built-in data 格式以及由行定義編碼器和解碼器提供的任何格式。
類別包含 Built-in types (Array, Dictionary, Optional)時也符合 Codable。
如果只需要用到 Encode 或 Decode 其中一個功能,只需要選擇實作 Encodable 或是 Decodable。
有時候抓取下來的 JSON 資料的鍵值與我們建構的型態屬性名稱不同時,可以宣告一個特殊的列舉(enum)稱作 CodingKeys 。
這個列舉有一個 String 形態的原始值,並實作 CodingKey 協定;這個列舉內,要定義資料模型內的屬性名稱及所對應的 JSON 內的鍵值,如果屬性名稱相同,則可以省略指定。
要處理嵌入式 JSON 物件,要另外定義一個列舉,並宣告 case 屬性名稱及其對應嵌入物件的鍵值。
因為它不是直接對映,需要實作 Decodable 協定的方法 init(from:),來處理所有屬性的解碼工作。在 init 方法,先以 CodingKeys.self 來呼叫解碼器(decoder)的 container(keyedBy:) 方法來取得跟特定編碼鍵有關的資料。
要解碼一個特定值,我們先以特定的鍵(例如 .name )呼叫 decode 方法,並關聯型態(例如 String.self)。title 屬性解碼方式需要一點技巧,必需要以 TheClassKeys.self 呼叫 nestedContainer 方法來取得嵌入 JSON 物件。值回傳後,然後我們進一步解碼 title 的值。