我正在尝试对数据进行编码和决定,编码工作非常顺利,但当我使用解码器对数据进行解码时,我的解码器函数会给我带来一个错误。请查看我的代码,让我知道我应该做什么才能正确解码数据。调试后我发现的问题是,解码器块在接下来的切换中没有进一步进行,而是在返回的类型上出错,找不到DecodingKey类型。
type=尝试container.decode(WorkoutType.self,forKey:.type(这是一行,当我想解码数据时,它不会继续。
这是我的代码
struct OverviewWorkout : Codable {
enum WorkoutType: String , Codable {
case workout
case coach
case bodyArea
case challenge
case title
case group
case trainer
}
enum WorkoutsData {
case workout(Workout)
case challenge(Workout)
case group([Workout])
case trainer([Trainer])
case bodyArea([Workout])
case coach(CoachInstruction)
case title(Title)
}
var type: WorkoutType
var data : WorkoutsData
init(from decoder: Decoder) throws {
print("decoder called")
let container = try decoder.container(keyedBy: CodingKeys.self)
type = try container.decode(WorkoutType.self, forKey: .type)
switch type {
case .workout, .challenge:
let data = try container.decode(Workout.self, forKey: .data)
self.data = .workout(data)
case .coach:
let data = try container.decode(CoachInstruction.self, forKey: .data)
self.data = .coach(data)
case .bodyArea:
let data = try container.decode([Workout].self, forKey: .data)
self.data = .bodyArea(data)
case .title:
let data = try container.decode(Title.self, forKey: .data)
self.data = .title(data)
case .group:
let data = try container.decode([Workout].self, forKey: .data)
self.data = .group(data)
// trainer data
case .trainer:
let data = try container.decode([Trainer].self, forKey: .data)
self.data = .trainer(data)
}
print("decodable called")
}
private enum CodingKeys: String, CodingKey {
case type,data
}
}
extension OverviewWorkout {
struct Title: Codable {
let title: String
}
}
extension OverviewWorkout {
func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
print(container)
switch data {
case .workout(let workout):
try container.encode(workout, forKey: .data)
case .bodyArea(let bodyarea):
try container.encode(bodyarea, forKey: .data)
case .title(let title):
try container.encode(title, forKey: .data)
case .coach(let coach):
try container.encode(coach, forKey: .data)
case .trainer(let trainer):
try container.encode(trainer, forKey: .data)
case .group(let group):
try container.encode(group, forKey: .data)
default:
print("out of range")
}
}
}
每当调用init(来自decoder:decoder(throws时,我都会遇到以下错误keyNotFound(编码键(字符串值:"type",intValue:nil(,Swift。DecodingError.Context(编码路径:[_JSONKey(字符串值;"Index 0",intValue:0(],debugDescription:";没有与键CodingKeys(字符串值:"type",intValue:nil(("type"(关联的值&";,underlyingError:nil((keyNotFound(编码键(字符串值:"type",intValue:nil(,Swift。DecodingError.Context(编码路径:[_JSONKey(字符串值;"Index 0",intValue:0(],debugDescription:(lldb(
所以问题是我只是对数据进行编码,而不是密钥,这就是为什么我在解码数据时确实遇到了密钥为零的问题。我只放了一行代码来编码密钥,这就是所有的问题。