我已經閱讀了很多文章,但仍然找不到解決這種情況的最佳方法。我有不同的模型,用于根據單元格型別回傳。處理 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
}
}
uj5u.com熱心網友回復:
您可以使用如下定義的關聯值宣告 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 您可能已經訪問過]
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/367137.html
