Subclassing Swift class in Obj-c [Private-API Friday #1]

If you are in the migration process from Objective-C to Swift language, you maybe need to subclass some new Swift class back in objc. Today I will show you how you can do this and why you shouldn’t.

Investigation

Let’s create our guinea pig class.

Xcode checks for the attribute and macro existence and defines the new macro.

Implementation

Yes! Private API! Let’s trick Xcode by defining our own “SWIFT_CLASS.” I forget how to do this locally and will change GCC preferences instead. Let me know if you can make this locally.

Reasons

Objc is not a Swift. No, really, it’s very different languages under the hood. And with an easy bridging provided by Xcode this can be easily forgotten. I will add two simple functions to our example class:

  • Cycle bridging headers. You can’t use your subclass back in Swift, because Swift files should be compiled before your subclass, but they are using your class, so ¯\_(ツ)_/¯

Conclusions

Some rules and limitations exist for a reason. However, they shouldn’t be accepted just by the sole authority. Investigation of private APIs can be useful for better understanding system behavior and languages. It also can help to become a better public API developer. So I will start this series to share my insights from different hidden elements that I encounter.

MacOS and iOS dev. ObjC paradigm fan.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store