Codable
とは?
概要
Codable は、Swift4 から Foundation に追加されたプロトコルであり、Swift のデータ型とそのほかのプレーンな表現 (JSON等) との相互変換を容易にする。Decodable と Encodable の2つのプロトコルの組み合わせであり、これらは各々、対象のデータ型のエンコード, デコードのための振る舞いを定義させる。
code:swift
typealias Codable = Decodable & Encodable
Codable
これらのプロトコルを実装し、データ型を他のデータ表現と相互変換可能にするプロセスは、しばしば 型を Codable にする と言われる。
Encoding and Decoding Custom Types - Apple Developer
ユースケース
ネットワーク上でやり取りするデータを生成する際のエンコード/デコード
UserDefaults 等、DB に保存する際のエンコード/デコード
API やサービスに値を渡す際のエンコード/デコード
使い方
Codable な型たち
デフォルトで既に Codable な型がいくつか存在する。そして、これらのみをプロパティに持つ型も、また自動的に Codable になる。
Standard library types:
String, Int, Double, Array, Dictionary, Optional, ...
Foundation types:
Date, Data, URL, ...
エンコード/デコードする
エンコーダーとして標準で存在するのは PropertyListEncoder や JSONEncoder であり、Codable な型はこれらを利用してエンコード/デコードできるようになる。 
CodingKey
Codable な型は、その内部に CodingKey プロトコルに準拠した enum を保持できる。この enum の cases は、エンコード/デコード時に含まれるべきプロパティ名を列挙する。この enum の case は、各々それを含んでいる Codable な型のプロパティと一致している必要がある。
case 名が Codable な型のプロパティ名、case の raw value がエンコード後のプロパティに合致するようにエンコード/デコードされる。そのため、例えばエンコード後のプロパティ名をエンコード前のプロパティ名とは別のものに定義したい場合は、以下のように実現できる。
code:swift
struct Landmark: Codable {
var name: String
var foundingYear: Int
var location: Coordinate
var vantagePoints: Coordinate
enum CodingKeys: String, CodingKey {
case name = "title"
case foundingYear = "founding_date"
case location
case vantagePoints
}
}
https://developer.apple.com/documentation/swift/codingkey