0

I'm trying to create an object from a class that is passed on to a function of mine. The problem is that I'm unable to pass any arguments to its constructor because I can't seem to initialize the class with parameters.

This is the code I have so far:

class func invokeService<T: Initable>(service: String, returningClass: T.Type, completionHandler handler: ((T) -> ())) {

        var interfaceObject = returningClass()

        interfaceObject.self(data: service as Dictionary <String, AnyObject>)

        handler(interfaceObject)
    }

This is the error I get:

'(data: Dictionary <String, AnyObject>)-> $T2' is not identical to 'T'
danielrvt
  • 10,177
  • 20
  • 80
  • 121

1 Answers1

1

Some strange things are going on in your code, as far as I can see (I am no Swift expert either). Specifically, you are trying to initialise the same object twice.

I am assuming that your Initable protocol is defined as:

protocol Initable {
    init(data:Dictionary <String, AnyObject>)
}

And that you want to instantiate an object from that. Then the correct way to do that would be:

class func invokeService<T: Initable>(service: String, returningClass: T.Type, completionHandler handler: ((T) -> ())) {

    var dict = // create a Dictionary <String, AnyObject>
    var interfaceObject = returningClass(data: dict)

    handler(interfaceObject)
}

Now your remaining problem is how to convert the service to a dictionary. You cannot simply cast a string to a dictionary for obvious reasons.

You want to have a look at this answer to another question as well.

Pedantic note: using dynamic typing and initialising an anonymous class like this is very advanced usage that should only be needed in very extreme cases. Usually an Abstract Factory Pattern is a better way to achieve a similar goal.

Community
  • 1
  • 1
fishinear
  • 6,101
  • 3
  • 36
  • 84