0

I want to wrap data to JSON before sending.

func request(content: [String]) {
        
        try? JSONEncoder().encode(content)

This worked well when sending arrays of string. However, I would also like to send other structures that can be represented in JSON.

For example arrays containing arrays, or dictionaries.

My idea was to make it

func request(content: Any) {
        
        try? JSONEncoder().encode(content)

Which gives Protocol 'Any' as a type cannot conform to 'Encodable'

How can I make the parameter as generic as possible so what can be formed as JSON gets formed as JSON and whatever fails, fails? I do understand I can't JSONify everything but I would like to be able to do it with things that I know of can be represented in JSON form. I found things like this https://stackoverflow.com/a/64471720/2161301 but apparently you can't do that on "normal" functions

tw33
  • 31
  • 3
  • what do you mean by normal functions? The solution mentioned in the link you shared is the way to achieve what you are looking for. i.e. func request(content: T) {} – waseemwk Jul 12 '21 at 06:06
  • what problem are you facing with this approach? – waseemwk Jul 12 '21 at 06:07
  • Hey @waseemwk thank you for the example. One situation where it's not working is `let arr = ["a", ["b", "c"]] as [Any]`, then I get `Protocol 'Any' as a type cannot conform to 'Encodable'` – tw33 Jul 12 '21 at 19:10

1 Answers1

3

You can use AnyCodable in your project.

Then you will be allowed to use [String: AnyEncodable] / [AnyEncodable] etc. in the places where you are not able to use Any while trying to use JSONEncoder api.

Tarun Tyagi
  • 9,364
  • 2
  • 17
  • 30