【发布时间】: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