0

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. Commented Jun 15, 2019 at 7:39

1 Answer 1

1

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()
    }
}
Sign up to request clarification or add additional context in comments.

9 Comments

i want to add custom object in Model so that's why i add Timer in codable.
Yes, but you don't need to encode the Timer instance. Create it in the initializer when decoding the JSON/Property List.
Can you write sudo code or code here which you're saying. How to initialize Timer and add it in codable class object.
what is the name and why i need it?
i receiving nil object when i parse in codable class.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.