简体   繁体   English

如何在Swift中定义初始化泛型类型

[英]How to define of initializing generic type in Swift

I'm writing the function like this 我正在写这样的功能

func issueArrayFromResponse(response: DataResponse<Any>) -> Result<[Issue]> {}

However this kind of function appear many time, such as repoArrayFromResponse, gistArrayFromRespnse and so on. 但是这种功能出现了很多次,例如repoArrayFromResponse,gistArrayFromRespnse等。 So I tried to make these functions into one. 因此,我试图将这些功能合二为一。

func arrayFromResponse<T>(response: DataResponse<Any>) -> Result<[T]> {}

The problem is I don't have initializer for type T and don't know how to achieve it. 问题是我没有类型T的初始化程序,也不知道如何实现它。 In case issueArrayFromResponse , I have a class Issue and it has initializer: init(json: [[String: Any]]), so i was able to write 万一issueArrayFromResponse ,我有一个类Issue ,它具有初始化程序:init(json:[[String:Any]]),所以我能够写

issue = Issue(json: item)

However, in case arrayFromResponse<T> , the compiler says 'T' cannot be constructed because it has no accessible initializers 但是,在arrayFromResponse<T>情况下,编译器说'T' cannot be constructed because it has no accessible initializers

How can I make initializer for T? 如何为T创建初始化器?

I think the easiest way is to make protocol. 我认为最简单的方法是制定协议。 You can make such protocol: 您可以制定这样的协议:

protocol ResultProtocol {   
}

and confirm all your classes to this protocol 并确认您对该协议的所有类

class Issue: ResultProtocol {
    init(json: String) {

    }
}

then you can: 那么你也能:

func arrayFromResponse<T: ResultProtocol>(response: DataResponse<Any>) -> Result<[T]> {

    return Result<[T]>()

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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