【发布时间】:2020-08-10 08:17:13
【问题描述】:
为这个冗长的问题道歉。
我正在使用Firestore 来存储在线数据并具有如下所示的当前结构;
{
"activities": {
"mG47rRED9Ym4dkXinXrN": {
"createdAt": 1234567890,
"activityType": {
"title": "Some Title"
}
},
"BF3jhINa1qu9kia00BeG": {
"createdAt": 1234567890,
"activityType": {
"percentage": 50,
}
}
}
}
我正在使用 JSON 可解码协议来检索数据。我有一个主要结构;
struct Activity: Decodable {
let documentID: String
let createdAt: Int
let activityType: ActivityType
}
此结构包含必需的数据,例如 createdAt 和 documentID(即“mG47rRED9Ym4dkXinXrN”)。根据嵌套在“activityType”中的数据,它应该返回下面列出的两个结构之一;
struct NewGoal: Decodable {
let title: String
}
struct GoalAchieved: Decodable {
let percentage: Double
}
我正在使用可解码枚举来执行此操作;
enum ActivityType: Decodable {
case newGoal(NewGoal)
case goalAchieved(GoalAchieved)
}
extension ActivityType {
private enum CodingKeys: String, CodingKey {
case activityType
}
init(from decoder: Decoder) throws {
let values = try? decoder.container(keyedBy: CodingKeys.self)
if let value = try? values?.decode(GoalAchieved.self, forKey: .activityType) {
self = .goalAchieved(value)
return
}
if let value = try? values?.decode(NewGoal.self, forKey: .activityType) {
self = .newGoal(value)
return
}
throw DecodingError.decoding("Cannot Decode Activity")
}
}
当使用 Activity 结构作为我的数组时,我得到了 DecodingError。但是,当使用 ActivityType 作为我的数组时,它会很好地解码,但不会提供对 documentID 和 createdAt 的访问权限。我不能继承 Activity 结构,因为它是非协议的。请问我该如何构建这个?
【问题讨论】:
-
你能分享确切的解码错误信息吗?
-
这是我的代码“无法解码活动”中抛出的错误
-
它说明了原因吗?也许缺少钥匙?您是否尝试过将 CodingKeys 添加到 Activity 结构中?
标签: swift struct enumeration decodable