繁体   English   中英

如何处理 Codable Swift 中的任何类型的数据

[英]How Handle Any Type of Data in Codable Swift

我浏览了很多文章,但仍然找不到解决这种情况的最佳方法。 我有不同的模型,用于根据单元类型返回。 处理 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
    }
}

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

   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您可能已经访问过]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM