0

While creating a response model for an API when I initialize the variables and constants with the names that I am going to get from the API response I have to declare their types, i.e. String, Bool, Int.

My question is, is there any way that while initializing all this is there a way that I don't have to define the type of the variables or constants?

Because sometimes if I have declared a variable as String and in the response JSON the value of that key is Int the JSON decoder doesn't decode it and fails with an error.

So is there a library or something else I can use that will help me with this?

I have tried JSON decoder and mapper but they didn't or maybe I didn't do it right

EmilioPelaez
  • 18,758
  • 6
  • 46
  • 50
  • Swift is a strongly typed language. You can declare a property as `Any` but that is going to be a pain to deal with. You could use a custom decoder that converts the value from the JSON to a consistent type, but really the API should be fixed to be consistent – Paulw11 Mar 29 '22 at 11:07
  • 1
    An API that can return different types for a value is, in my opinion, poorly designed. If you have access to the API, my suggestion would be to fix the API instead. – EmilioPelaez Mar 29 '22 at 11:07
  • thanks both of you for the answers. you guys are right API should be fixed but i just wanted to learn a way of handling this problem and i just found out a way of doing this through a duplicate question but thank you for helping :D – Salman Sohail Mar 29 '22 at 11:16

0 Answers0