Reflection Call Method

As I understand it, the reflection in Swift is still poorly accessible. Currently, I am moving on to converting objective-c code to faster work (I noticed a significant difference).

Now I need a way to call a method using reflection. The object that you need to call the extends method NSObjectto resolve the class to solve using the following code:

let clazz = NSClassFromString("MyProject.DynamicClass") as NSObject.Type; 
let clazzInstance = clazz() as! NSObject;

I can get the number of arguments and a method reference using the following code:

let selectorMethod = Selector("myCustomMethod:");

let numberOfArguments : UInt32 = method_getNumberOfArguments(selectorMethod);
let referenceToMethod : Method = class_getInstanceMethod(clazz, selector!);

But how to use / call referenceToMethod?

Additionally,
I also tried calling performSelector, but it was completely removed by Swift 2. I would also like to prevent the use of any attributes @objc/ annotations.

+4
source share
2

Swifty , , , , NSObject, , , . :

class A{

    required init(){

    }
    func printSomething(s:String){

        println(s)
    }
}

// initializing object dynamically from class
let clazz = NSClassFromString("MyProject.A") as! A.Type   
let clazzInstance = clazz()

// getting and calling its methods in Swifty way    
let method = clazzInstance.printSomething 
method("something")

, ,

+1

, :

var :

var myFunctionToBe : (() -> AnyObject)?

AnyObject , :

init() {
    myFunctionToBe = {
       //do something
       return whatsdone
    }
}

var myFunctionToBe, :

let method = c.value as? (() -> AnyObject)

:

method!()

let returnVal = method!() as? String
0

All Articles