簡體   English   中英

TimeInterval 類型的編碼和解碼枚舉

[英]Encoding and decoding enum of type TimeInterval

給出的是以下枚舉:

    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
        }
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM