TimeInterval类型的编码和解码枚举

问题描述 投票:0回答:1

给出以下枚举:

    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的类型别名),但我不知道如何使用它们的名称进行编码和解码。有任何提示吗?

swift codable
1个回答
0
投票

由于您已对计时值进行了硬编码,因此建议您切换到基于字符串的枚举:

enum TimerType: String, Codable {

    case timer, `break`

    var timerValue: TimeInterval {
        switch self {
        case .timer: return 60 * 25
        case .break: return 60 * 5
        }
    }
}

© www.soinside.com 2019 - 2024. All rights reserved.