简体   繁体   English

如何创建嵌套的 Encodable class 并从 Swift 中的 function 返回它?

[英]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 项目中,我想执行以下操作:

  • create an Encodable class (named ChannelAnswer ) which has multiple attributes, including another generic Encodable object创建一个具有多个属性的Encodable class(名为ChannelAnswer ),包括另一个通用Encodable object
  • pass an instance of that class as an argument of a function or return it from a function将 class 的实例作为 function 的参数传递或从 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:现在,如果我想从 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM