[英]How to create a nested Encodable class and return it from a function in Swift?
In my iOS project, I want to do the following:在我的 iOS 项目中,我想执行以下操作:
Encodable
class (named ChannelAnswer
) which has multiple attributes, including another generic Encodable
objectEncodable
class(名为ChannelAnswer
),包括另一个通用Encodable
objectHere 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:现在,如果我想从 function 返回 class 的实例,如下所示:
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).问题是:
data
属性可以是任何类型,我只知道该类型是Encodable
(为了简单起见,上面的test()
function 只是一个例子)。
So how can I create my ChannelAnswer
class and successfully pass it as an argument of a function or return it from a function?那么如何创建
ChannelAnswer
class 并将其作为 function 的参数成功传递或从 function 返回?
Thanks.谢谢。
What you need is a generic method.您需要的是一种通用方法。
func test<T: Encodable>(data: T) -> ChannelAnswer<T> {
// ...
return ChannelAnswer("abc", data)
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.