Swift 4:如何为json不同类型的数组实现可编码协议

Swift 4: how to implement codable protocol for json array of different types

有人可以启发我如何实现 codable protocol 到 swift 结构,用于以下 json 多类型数组吗?

在下面的json素材数组中,可以是倒影物件,视频或音符物件。

{
  "materials": [
    {
      "reflection": {
        "title": "3-2-1 reflection",
        "description": "please reflect after today",
        "questions": [
          {
            "question": "question 1",
            "answer": "answer 1",
            "answerImageUrl": "http://xxx"
          },
          {
            "question": "question 1",
            "answer": "answer 1",
            "answerImageUrl": "http://xxx"
          }
        ]
      }
    },
    {
      "video": {
        "title": "the jungle",
        "description": "please watch after today lesson",
        "videoUrl": "http://"
      }
    },
    {
      "note": {
        "title": "the note",
        "description": "please read after today lesson"
      }
    }
  ]
}

如果您可以接受具有三个可选属性的 Material,这非常简单:

struct Response: Codable {
    let materials: [Material]
}

struct Material: Codable {
    let reflection: Reflection?
    let video: Video?
    let note: Note?
}

struct Video: Codable {
    let title, description, videoUrl: String
}

struct Reflection: Codable {
    let title, description: String
    let questions: [Question]
}

struct Question: Codable {
    let question, answer, answerImageUrl: String
}

struct Note: Codable {
    let title, description: String
}

let response = JSONDecoder().decode(Response.self, from: data)