mardi 15 septembre 2020

Is it possible to call generic object constructor using reflection in swift?

let's say we have a class

class Test: NSObject {
    
    let batman: String
    let spiderman: Int
    let superman: NSObject
    
    init(batman: String, spiderman: Int, superman: NSObject) {
        self.batman = batman
        self.spiderman = spiderman
        self.superman = superman
    }
}

And a generic method for initialization:

func resolve<T: NSObject>(args: Any...) throws -> T  {
        // if let object = initWithReflectionSomeHow(T.className, arg1, arg2...) {
        //     return object
        // } else {
        //     throw exception
        // }
    }

I found a way to to this without parameters like this:

func resolve<T: NSObject>() throws -> T  {
        if let objectClass = NSClassFromString(T.className) as? T.Type {
            let object = objectClass.init()
            return object
        } else {
            //throw classNotFoundException
        }
    }

So I would just call:

let obj = try resolve() as Test

but not sure how I can inject parameters. Is it even possible?





Aucun commentaire:

Enregistrer un commentaire