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. Let's assume I have a Tweet
class and User
class.
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
. Sample request from 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.
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
How can I access my Generic Type Class
in a generic way? Meaning that i'll pass the Class
type and be able to apply it to 'T'. I've tried passing it theu the input parameters but it won't help. I just can't figure it out. Any ideas?