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?
Asked
Active
Viewed 3,988 times
4

MatterGoal
- 16,038
- 19
- 109
- 186
-
Have a look at [`Mirror`](https://developer.apple.com/library/prerelease/ios/documentation/Swift/Reference/Swift_Mirror_Structure/index.html#//apple_ref/swift/struct/s:Vs6Mirror) type and [`CustomReflectable`](https://developer.apple.com/library/prerelease/ios/documentation/Swift/Reference/Swift_CustomReflectable_Protocol/index.html#//apple_ref/swift/intf/s:Ps17CustomReflectable) protocol. Not exactly the list of available functions out-of-the-box, but maybe you can just implement `CustomReflectable` in a way that will do what you need. – 0x416e746f6e Mar 02 '16 at 10:54
-
Swift reflection is not as mighty as we could expect it, in particular with regard to made experiences in more established languages, like Java. In fact, the reflection API has changed dramatically since Swift 2.0 and also has lost some functionality. An easy way to workaround are helper methods in your class and hardcode your "reflective" Information. Not nice, not beauty but it works. Sorry for that sobering response :( Supplement: For this purpose you could use the CustomReflectable, like Anton said. – Guardian667 Mar 02 '16 at 10:58
-
Swift has no official reflection right now. – Sulthan Mar 02 '16 at 12:26
1 Answers
5
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
.

Code Different
- 90,614
- 16
- 144
- 163
-
`Objective-C runtime functions are still available in Swift`-- except for Server-side Swift :). – Chris Prince Apr 08 '17 at 04:35
-
1Sadly Apple seem to have patched this. running the snippet above produces only `init` for me. – Aswath Aug 24 '22 at 08:53