简体   繁体   English

Swift:尝试创建通用类型的初始值设定项

[英]Swift: Trying to create a generic type initializer

I'm banging my head over here 我在这

. I'm trying to solve this "easy" to understand issue. 我正在尝试解决这个“容易”的问题。 I have an API Endpoint which i'm sending to request from many different classes. 我有一个API Endpoint ,我正在向许多不同的类发送请求。 Let's assume I have a Tweet class and User class. 假设我有一个Tweet类和User类。

class Tweet {

    var id: String!
    var description: String!

    required init() { }

 }

class User {

    var id: String!
    var username: String!
    var likes : Int!

    required init() { }

 }

Now, Depending on the Class request origin, I'll get a respond with an Array that each element holds the exact same properties as the source Class as JSON . 现在,根据Class请求的来源,我将得到一个Array响应,其中每个元素都具有与源Class JSON完全相同的属性。 Sample request from Tweet Class : 来自Tweet Class样本请求:

  "data":
  [{
     {
     "id": "492",
     "description": "HELP!"
     },
     {
     "id": "574",
     "description": "ME!"
     }
   ]}

Now, I'm trying to create a Generic Method which automatically parse those into an Array with objects from the passes Class type. 现在,我正在尝试创建一个Generic Method ,该Generic Method将具有传递Class类型的对象自动将其解析为一个Array This is what i've tried 这就是我尝试过的

func sendRequest<T>(resource: T.Type,withProperyList propList : [String], completion: @escaping ([T]?) -> ()) { 


// Create NSURLSession request, fetching data.. converting to json..

guard let mainArray = json["data"] as? NSArray else { return }

for element in mainArray  {

      let tweet = T() // **Error here**

 }

Error: ** 'T' cannot be constructed because it has no accessible initializers 错误:**'T'无法构造,因为它没有可访问的初始化程序

How can I access my Generic Type Class in a generic way? 如何以通用方式访问我的Generic Type Class Meaning that i'll pass the Class type and be able to apply it to 'T'. 这意味着我将传递Class类型并将其应用于'T'。 I've tried passing it theu the input parameters but it won't help. 我尝试将其传递给输入参数,但无济于事。 I just can't figure it out. 我只是想不通。 Any ideas? 有任何想法吗?

代替T() ,试试看。

let tweet = resource.init()

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

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