为略有不同的 json 响应创建通用编码 - Swift

Create common codable for slightly different json responses - Swift

如何在 swift 中为略有不同的 json responses.For 示例创建通用的可编码结构 response AB 具有几乎相同的属性并且 B 有一些名为 Designation 的额外属性。是否可以为这种情况创建通用的可编码结构?

//Response A
{
  "name" : "Jhon",
  "age" : 23,
  "mobile" : "+11012341234",
  .
  .
  .
}

//Response B
{
  "name" : "Jhon",
  "age" : 23,
  "mobile" : "+11012341234",
  .
  .
  .
  "designation": "Manager"
}

您可以像这样使用可选值:

struct Response: Decodable {

   var name: String
   var age: Int
   var mobile: String
   var designation: String?

   // If you need to decode, it would look like this:
   init(from decoder: Decoder) throws {

      let container = try decoder.container(keyedBy: CodingKeys.self)

      name = try container.decode(String.self, forKey: .name)
      age = try container.decode(Int.self, forKey: .age)
      mobile = try container.decode(String.self, forKey: .mobile)

      // Decode designation if provided
      if container.contains(.designation){
         designation = try container.decode(String.self, forKey: .designation)
      }
   }
}