In my iOS project, I want to do the following:
- create an
Encodable
class (namedChannelAnswer
) which has multiple attributes, including another genericEncodable
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.
What you need is a generic method.