0
votes

I'm facing an issue with codable. I'm not able to understand how to init custom timer object in codable class.

    class ShelfItem: Codable {

      var objTimer = Timer()

or i try to do it like

     // var objTimer: Timer()
    }

but it show me the error that is "Type 'ShelfItem' does not conform to protocol 'Encodable'"

1
The var objTimer = Timer() doesn’t make sense (a timer with no handler and no specified time to fire). And var objTimer: Timer() is just syntactically incorrect. But let’s set that aside and ask what you’re expecting to be encoded: As vadian said, it doesn’t make sense to encode/decode a Timer, itself, so you’d either exclude it from coding or take the unusual step to encode/decode enough so the timer could be reconstituted later (which is a strange notion with timers). Perhaps you can describe why you’re trying to encode/decode a timer and describe what you’re hoping to achieve. - Rob

1 Answers

0
votes

It makes no sense to en-/decode a Timer object.

To exclude objTimer from encoding add CodingKeys for the other properties and omit objTimer.

Simple example (in most cases you don't even need a class)

struct ShelfItem : Codable {
    let name : String
    var timer : Timer

    private enum CodingKeys : String, CodingKey { case name }

    init(from decoder : Decoder) throws
    {
        let container = try decoder.container(keyedBy: CodingKeys.self)
        name = try container.decode(String.self, forKey: .name)
        timer = Timer()
    }
}