【发布时间】:2018-06-02 08:48:39
【问题描述】:
如何使用 Swift Codable 协议将存储在 Swift 中的数据作为对象数组(只有 2 个值)解码/编码为(JSON 或其他类型的数据表示;应该无关紧要)key = value结构如下:
如您所见,它是一个timestamp = value 符号结构(我对时间戳的格式没有任何问题,没关系)
(我知道之前已经回答过关于存储在键中的数据的问题,但是我的问题不同,因为它特定于对象数组,只有 2 个值在平面键 = 值结构中转码)。
这是我处理 2 个对象的代码:
MetricResult = 包含时间戳和测量值
MetricResults = 包含应正确编码的 MetricResult 数组。
我已经为MetricResult 进行了编码,但是在阅读时我不知道如何处理包含实际数据本身的变量键。
struct MetricResult : Codable {
var date = Date()
var result = Int(0)
func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: Date.self)
try container.encode(result, forKey: date)
}
init(from decoder: Decoder) throws {
//how do deal with variable key name here??
}
}
struct MetricResults: Codable {
var results = [MetricResult]()
func encode(to encoder: Encoder) throws {
//how do deal with variable key name here??
}
init(from decoder: Decoder) throws {
//how do deal with variable key name here??
}
}
extension Date: CodingKey {
//MARK: - CodingKey compliance
public init?(intValue: Int) {
return nil
}
public init?(stringValue: String) {
self.init(stringFirebase: stringValue)
}
public var intValue: Int?{
return nil
}
public var stringValue: String {
return stringFirebase()
}
}
【问题讨论】: