Help us understand the problem. What is going on with this article?

Decodableオブジェクトのサブクラスを作成して、値を追加でデコードする方法

More than 1 year has passed since last update.

基本的には、サブクラスを生成するよりoptionalで宣言した方がいいような気がしますが、どうしてもサブクラスでやらないといけないことがあったので、そのやり方について書きます。

サンプル

以下の二つのJSONをデコードする想定にします。

person.json
{
    "name": "Mery Jane Watson",
    "work": "actress"
}
hero.json
{
    "name": "Peter Parker",
    "work": "hero",
    "hero_name": "SpiderMan",
    "costume_colors": ["red", "blue", "black"]
}

まずは人間用のクラスを作成します。

Person.swift
class Person: Decodable {
    var name: String
    var work: String

    private enum CodingKeys: String, CodingKey {
        case name
        case work
    }
}

続いてヒーロー用のクラスも用意します。

Hero.swift
class Hero: Person {
    var heroName: String
    var costumeColors: [String]

    private enum CodingKeys: String, CodingKey {
        case heroName = "hero_name"
        case costumeColors = "costume_colors"
    }

    required init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)
        self.heroName = try container.decode(String.self, forKey: .heroName)
        self.costumeColors = try container.decode([String].self, forKey: .costumeColors)
        try super.init(from: decoder)
    }
}

メリット

・どうしてもoptionalを使いたくない場合に使える

デメリット

・structが使用できなくなるので、値渡しと参照渡しに気をつけないと死ぬ(私は一度死にました。)

fr0g_fr0g
ダブルフロッグ
andfactory
Smartphone Idea Companyとして、人々の生活に「&(アンド)」を届ける。
https://andfactory.co.jp/
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした