给出以下枚举:
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"
}
}
我想将其值保存在使用此枚举对json的结构中,如下所示:
{
"type": "timer"
}
但是实际上它是
{
"type": 1500
}
虽然我可以看到它实际上保存了Double
值(因为它是TimerInterval
类型,它是Double的类型别名),但我不知道如何使用它们的名称进行编码和解码。有任何提示吗?
由于您已对计时值进行了硬编码,因此建议您切换到基于字符串的枚举:
enum TimerType: String, Codable {
case timer, `break`
var timerValue: TimeInterval {
switch self {
case .timer: return 60 * 25
case .break: return 60 * 5
}
}
}