0

In my iOS project, I want to do the following:

  • create an Encodable class (named ChannelAnswer) which has multiple attributes, including another generic Encodable object
  • pass an instance of that class as an argument of a function or return it from a function

Here is what I tried:

class ChannelAnswer<T> : Encodable where T : Encodable
{
    let errorCode: String?
    let data: T?
    let origin: Int = 2

    init(_ errorCode: String?, _ data: T? = nil)
    {
        self.errorCode = errorCode
        self.data = data
    }
}

Now, if I want to return an instance of that class from a function, like the following:

func test() -> ChannelAnswer
{
    ...
    return ChannelAnswer("abc", anyEncodableObject)
}

I get the following error:

Reference to generic type 'ChannelAnswer' requires arguments in <...>

The thing is: the data attribute could be of any type, I only know that that type is Encodable (the test()function above is just an example for the sake of simplicity).

So how can I create my ChannelAnswer class and successfully pass it as an argument of a function or return it from a function?

Thanks.

matteoh
  • 2,810
  • 2
  • 29
  • 54
  • 1
    "the data attribute could be of any type" What do you mean by this? Can you show some meaningful code to demonstrate? Right now it looks like it can only be `String`. – Sweeper Jun 04 '22 at 11:35

1 Answers1

1

What you need is a generic method.

func test<T: Encodable>(data: T) -> ChannelAnswer<T> {
    // ...
    return ChannelAnswer("abc", data)
}
Leo Dabus
  • 229,809
  • 59
  • 489
  • 571
  • ...And to read about generics in docs (https://docs.swift.org/swift-book/LanguageGuide/Generics.html). ;) – lazarevzubov Jun 04 '22 at 13:07
  • Thanks, but the `ChannelAnswer` parameters ar actually built inside the `test()` function, the `data` can't be passed as a parameter of `test()` then... – matteoh Jun 04 '22 at 14:48
  • @matteoh So edit your question and post your code. Please make sure to provide a [mcve] – Leo Dabus Jun 04 '22 at 19:31