Home > Mobile >  How Handle Any Type of Data in Codable Swift
How Handle Any Type of Data in Codable Swift

Time:11-25

I have gone through many articles but still could not find a best approach to tackle this situation . I am having different models , that are used to be returned on the basis of type of cell . What is the best approach to handle with Any data type (Any consists of more than three different data models ). See my code below

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
    }
}

CodePudding user response:

You can declare the Type enum with associated values as defined below:

   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)
        .
        .
        .

        }
       
    }
 }

I was short of time so couldn't compile it but I hope you this will give you an idea. Additionally, Sharing a reference article for you. [:D You might have visited already]

  • Related