12

API エンドポイントから返されたデータからビューをレンダリングしようとしています。私のJSONは(おおよそ)次のようになります。

{
  "sections": [
    {
      "title": "Featured",
      "section_layout_type": "featured_panels",
      "section_items": [
        {
          "item_type": "foo",
          "id": 3,
          "title": "Bisbee1",
          "audio_url": "http://example.com/foo1.mp3",
          "feature_image_url" : "http://example.com/feature1.jpg"
        },
        {
          "item_type": "bar",
          "id": 4,
          "title": "Mortar8",
          "video_url": "http://example.com/video.mp4",
          "director" : "John Smith",
          "feature_image_url" : "http://example.com/feature2.jpg"
        }
      ]
    }    
  ]
}

UI でビューをレイアウトする方法を表すオブジェクトがあります。次のようになります。

public struct ViewLayoutSection : Codable {
    var title: String = ""
    var sectionLayoutType: String
    var sectionItems: [ViewLayoutSectionItemable] = []
}

ViewLayoutSectionItemableレイアウトで使用する画像のタイトルと URL などを含むプロトコルです。

ただし、sectionItems配列は実際にはさまざまな型で構成されています。私がやりたいのは、各セクション項目を独自のクラスのインスタンスとしてインスタンス化することです。

その JSON 配列内のアイテムを反復処理し、それぞれの場合に適切なクラスのインスタンスを作成できるようにするには、init(from decoder: Decoder)メソッドをどのようにセットアップすればよいでしょうか?ViewLayoutSection

4

5 に答える 5