[英]Decoding Codable Throwing Nil Key not found
我正在嘗試編碼並確定數據和編碼工作得很好但是當我使用解碼器解碼數據時,我的解碼器 function 給我一個錯誤。 請查看我的代碼,讓我知道我應該怎么做才能正確解碼數據。 調試后我發現的問題是解碼器塊在切換后沒有繼續進行,而是在返回類型時出現錯誤,未找到 DecodingKey 類型。
type = try 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(from decoder: Decoder) 拋出時遇到的錯誤 keyNotFound(CodingKeys(stringValue: "type", intValue: nil), Swift.DecodingError.Context(codingPath: [_JSONKey(stringValue: "Index 0" , intValue: 0)], debugDescription: "No value associated with key CodingKeys(stringValue: "type", intValue: nil) ("type").", underlyingError: nil)) keyNotFound(CodingKeys(stringValue: "type", intValue: nil), Swift.DecodingError.Context(codingPath: [_JSONKey(stringValue: "Index 0", intValue: 0)], debugDescription: (lldb)
所以問題是我只是在編碼數據而不是密鑰,這就是為什么我在解碼數據時確實遇到了密鑰為 Nil 的問題。 我剛剛輸入了一行代碼來對密鑰進行編碼,這就是所有問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.