Jay
Jay

Reputation: 99

Why initializing JSONdecoder?

When looking at coding examples on how to use the JSONDecoder in Swift, most often it is first being initialised and then used. Something along those lines:

let decoder = JSONDecoder()
decoder.decode(...)

All that usually sits within a function. What I am wondering is why doesn't the JSONDecoder be directly used? I.e. JSONDecoder().decode(...). This should also work and lead to less code. Also, initialisation would anyway happen for each function call separately, so it sohuld be the same from an efficiency perspective. Am I missing something?

Upvotes: 1

Views: 132

Answers (1)

Luca Sfragara
Luca Sfragara

Reputation: 644

No, you are right. However, most times developers set other properties, like the decoding strategy of the object, and then use it. So it makes sense to first initialize it, set the properties/option, and then decode.

Upvotes: 2

Related Questions