【问题标题】:How Handle Any Type of Data in Codable Swift如何在 Codable Swift 中处理任何类型的数据
【发布时间】:2021-12-29 10:04:38
【问题描述】:

我浏览了很多文章,但仍然找不到解决这种情况的最佳方法。我有不同的模型,用于根据单元格类型返回。处理 Any 数据类型的最佳方法是什么(Any 包含三个以上不同的数据模型)。请参阅下面的代码

import Foundation


struct OverviewWorkout : Decodable {
    
    enum WorkoutType: String, Codable {
        case workout
        case coach
        case bodyArea
        case challenge
        case title
        case group
        case trainer
    }

    var type: WorkoutType
    var data : Any

    init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)
        type = try container.decode(WorkoutType.self, forKey: .type)
        switch type {
        case .workout, .challenge:
            data = try container.decode(Workout.self, forKey: .data)
        case .coach:
            data = try container.decode(CoachInstruction.self, forKey: .data)
        case .bodyArea:
            data = try container.decode([Workout].self, forKey: .data)
        case .title:
            data = try container.decode(Title.self, forKey: .data)

        case .group:
            data = try container.decode([Workout].self, forKey: .data)
      // trainer data
        case .trainer:
            data = try container.decode([Trainer].self, forKey: .data)

        }
       
    }

    private enum CodingKeys: String, CodingKey {
        case type,data
        
    }
}

extension OverviewWorkout {
    struct Title: Codable {
        let title: String
    }
}

【问题讨论】:

  • 不要使用Any,使用带有关联值的枚举。
  • 你能解释一下你的答案吗?

标签: ios json swift parsing codable


【解决方案1】:

您可以使用如下定义的关联值声明类型枚举:

   struct OverviewWorkout : Decodable {

      var type: WorkoutType 

      enum WorkoutType: String, Codable {
        case workout(data: Workout)
        case coach(data: CoachInstruction)
        case bodyArea(data: [Workout])
        case title(data: Title)
        case group(data: [Workout])
        case trainer(data: Trainer)
    }

   init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)
        type = try container.decode(WorkoutType.self, forKey: .type)
        switch type {
        case .workout:
            let data = try container.decode(Workout.self, forKey: .data)
            self = .workout(data: data)
        case .trainer:
            let data = try container.decode(Trainer.self, forKey: .data)
            self = .trainer(data: data)
        .
        .
        .

        }
       
    }
 }

我时间紧迫,无法编译它,但我希望这会给你一个想法。此外,为您分享参考文章。 [:D 你可能已经访问过]

【讨论】:

  • 感谢您的快速响应,这似乎现在可以工作,但我发现另一个问题,即编码部分工作得很好,但是当我解码时它说没有找到密钥“类型” .这个问题的原因可能是什么?任何建议
  • 然后将类型键设为可选。这肯定意味着 json 中的键名不同,或者某些对象不存在该键名。如果您不这么认为,请在此处分享您收到此错误的 json 响应。
  • 抱歉忘了提,但我也通过编码密钥解决了这个问题。这就是我所缺少的。非常感谢。
  • 太好了,如果对您有帮助,请您为答案投票。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-02-19
  • 1970-01-01
  • 2019-03-11
  • 2015-12-13
  • 2018-06-09
相关资源
最近更新 更多