[英]Encoding and decoding enum of type TimeInterval
Given is the following enum:给出的是以下枚举:
enum TimerType: TimeInterval, Codable {
case timer, `break`
var rawValue: TimeInterval {
switch self {
case .timer: return 60 * 25
case .break: return 60 * 5
}
}
enum CodingKeys: String, CodingKey {
case timer = "timer"
case `break` = "break"
}
}
I want save its values in structs that are using this enum to json like this:我想将其值保存在使用此枚举到 json 的结构中,如下所示:
{
"type": "timer"
}
But what it actually does is但它实际上做的是
{
"type": 1500
}
While I can see that it actually saves the Double
value (as it's of type TimerInterval
which is a typealias of Double), I cannot figure out how to encode and decode with their names.虽然我可以看到它实际上保存了
Double
值(因为它是TimerInterval
类型,它是 Double 的类型别名),但我无法弄清楚如何使用它们的名称进行编码和解码。 Any hints?有什么提示吗?
Since you have the timing values hardcoded, I would suggest switching to a String-based enum:由于您对时间值进行了硬编码,因此我建议切换到基于字符串的枚举:
enum TimerType: String, Codable {
case timer, `break`
var timerValue: TimeInterval {
switch self {
case .timer: return 60 * 25
case .break: return 60 * 5
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.