2

I'm developing a HTML5 showcase application and I need to discover all the methods in my Swift protocols. All the protocols extends from a base protocol.

The application is a HTML5 showcase for testing this methods. The app calls the method and gives the response.

I found some information about one specific protocol but i need to discover all the protocols in my app and then all the information (name, arguments name arguments type and return values) about this methods.

@objc protocol Protocol {    
    func method1()
    func method2() -> Bool
    func method3(param1:Int) -> Bool
    func method4(param1:Int, param2:Int, param3:Int) -> Bool
}

var numMethods:UInt32 = 0
var methods:UnsafeMutablePointer<objc_method_description> = protocol_copyMethodDescriptionList(Protocol.self, true, true, &numMethods)

for var iuint:CUnsignedInt = 0; iuint < numMethods; iuint++ {

    var i:Int = Int(iuint)
    var method:objc_method_description = methods[i]    
    println("Method #\(i): \(method.name)")
}

I'm using Objective-C Runtime Reference

Any ideas how to do this in swift?

ikocel1
  • 1,212
  • 1
  • 9
  • 9

2 Answers2

1

You are going to want to get:

  1. the method implementation (method_getImplementation) https://developer.apple.com/library/mac/documentation/Cocoa/Reference/ObjCRuntimeRef/index.html#//apple_ref/c/func/method_getImplementation
  2. and the method selector (method_getName) https://developer.apple.com/library/mac/documentation/Cocoa/Reference/ObjCRuntimeRef/index.html#//apple_ref/c/func/method_getName

Then in objective-c (using a bridged file, of course), cast the method implementation (i.e. IMP) as a function pointer. Then call the function pointer in objective-c with the

  1. target
  2. selector
  3. and any parameters you may have

    id (*func)(id, SEL, id) = (void *)imp;
    return func(target, selector, param);`
    

Take a look at how in this blog post he calls the init method and that should help as well. http://ijoshsmith.com/2014/06/05/instantiating-classes-by-name-in-swift/

leogdion
  • 2,332
  • 1
  • 19
  • 21
0

There is no real reflection in swift.

For more reading, please read:

  1. Does Swift support reflection?
  2. How do I print the type or class of a variable in Swift?
  3. http://waffletower.blogspot.sg/2014/06/swift-doesnt-have-much-objective-c.html
  4. https://github.com/mikeash/MAObjCRuntime
Community
  • 1
  • 1
ytbryan
  • 2,644
  • 31
  • 49
  • Thanks for the documentation. I read all this posts before. But in this one http://stackoverflow.com/a/24072677/2248121 says that is possible query for the methods using the Objective-C Runtime Reference, that's exaclly what i'm doing. I'm asking if someone has a full example of getting all the information of a method. – ikocel1 Oct 09 '14 at 11:44