I try to instanciate a new class from a string class name, like we can easy do in Java. I have finally wrote this function:
func stringClassFromString(_ className: String) -> AnyClass! {
let namespace = Bundle.main.infoDictionary!["CFBundleExecutable"] as! String;
let cls: AnyClass = NSClassFromString("\(namespace).\(className)")!;
return cls;
}
Thanks to some googling, but as soon as I tried this solution thanks to a unit test :
func test() {
let myclass = stringClassFromString("NSDate") as! NSDate.Type
let instance = myclass.init()
print(instance)
}
I have an exception (Thread 1: EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0)) as soon as my test use the line : let namespace... I tried to see the content of the infoDictionary, he's empty. So my question is simple, is it because of the unit tests context that my dictionary is empty ? Is there any method or library (like robolectric for android) to simulate an infoDicionary for testing purpose.
Aucun commentaire:
Enregistrer un commentaire