Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reflection with Swift - Get functions name of a class [duplicate]

Tags:

swift

I wonder if there is a way to get some useful information of a class composition. As example I'd find extremely useful to be able to access all the functions available for a class. It seems that the MyrrorType is not what I'm looking for though :/ I know that I can obtain the function name using __FUNCTION__ but this is not exactly what I need. What I need is a full list of all the functions available for class. any useful hints?

like image 603
MatterGoal Avatar asked Oct 20 '25 16:10

MatterGoal


1 Answers

Reflection in Swift is very limited compared to the hackeries available in Objective-C. Having said that, the Objective-C runtime functions are still available in Swift. You can sneak your class into the Objective-C world by making it inherit from NSObject:

class MyClass: NSObject {
    func f1() {}
    func f2() {}
    func f3() {}
}

let myClass = MyClass.self

var methodCount: UInt32 = 0
let methodList = class_copyMethodList(myClass, &methodCount)

for i in 0..<Int(methodCount) {
    let selName = sel_getName(method_getName(methodList[i]))
    let methodName = String(CString: selName, encoding: NSUTF8StringEncoding)!
    print(methodName)
}

This will give you 4 methods: f1 ... f3 and init.

like image 139
Code Different Avatar answered Oct 22 '25 06:10

Code Different



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!