相关疑难解决方法(0)

如何在Swift 4中实现JSON数据的多态解码?

我正在尝试从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"
        }
      ]
    }    
  ]
}
Run Code Online (Sandbox Code Playgroud)

我有一个对象,表示如何在我的UI中布局视图。看起来像这样:

public struct ViewLayoutSection : Codable {
    var title: String = ""
    var sectionLayoutType: String
    var sectionItems: [ViewLayoutSectionItemable] = []
}
Run Code Online (Sandbox Code Playgroud)

ViewLayoutSectionItemable 是一种协议,其中包括要在布局中使用的图像的标题和URL。

但是,sectionItems数组实际上由不同的类型组成。我想做的是将每个小节实例化为自己类的实例。

如何设置的init(from decoder: Decoder)方法,ViewLayoutSection以便让我遍历该JSON数组中的项目并在每种情况下创建适当的类的实例?

json swift codable

9
推荐指数
3
解决办法
1494
查看次数

标签 统计

codable ×1

json ×1

swift ×1