9

Something like objc_getClassList but for structs.

Just to give some context: this method (for classes) is used in our unit tests to test that all classes with certain suffix have tests for them. We test the tests!

5
  • 1
    As far as I know, structs don't really exist at run time. They're just a way of telling the compiler how to handle related data that's grouped together. In most cases (i.e. when not using protocol polymorphism), the methods are completely inlined, and there's no need for any kind of runtime knowledge of the struct existing
    – Alexander
    Commented Jan 24, 2017 at 14:10
  • @Alexander and if all structs conform to some single protocol? There are hints that you may be able to use Mirror(reflecting: Protocol.self).children at some point in time, but in current Swift version the array is empty. stackoverflow.com/questions/35125708/… Commented Jan 24, 2017 at 15:54
  • Protocols also can't get compiled away. If the compiler has sufficient information to be able to statically dispatch all methods of a protocol, there's no reason for it exist at run time.
    – Alexander
    Commented Jan 24, 2017 at 15:59
  • In general, Swift takes a much different approach than ObjC. In ObjC, no classes were ever dissolved. They were always kept in the compiled code so that they can be tinkered with in the runtime. This means all methods are always dynamically dispatched, all ivars and properties are dynamically accessed, etc. This has significant runtime cost, that was rarely worth it, because few people ever took advantage of this dynamism. Swift tries to optimise away as much as it can. Object instantiations can be illuded, methods are be devirtualized, generics are specialized, etc.
    – Alexander
    Commented Jan 24, 2017 at 16:03
  • If you want this ObjC level dynamism, and you find the performance cost to be justifiable, then you can stick to just using @objc, or inheriting from NSObject
    – Alexander
    Commented Jan 24, 2017 at 16:05

1 Answer 1

1

The Swift compiler mostly emits enough metadata to do this kind of reflection today but it isn't exposed. Full-fidelity reflection is on the "list of things we'd like to do" but has not yet been implemented.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.