How to create a nested Encodable class and return it from a function in Swift?

116 Views Asked by At

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.

1

There are 1 best solutions below

3
On

What you need is a generic method.

func test<T: Encodable>(data: T) -> ChannelAnswer<T> {
    // ...
    return ChannelAnswer("abc", data)
}