0

This question isn't about bridging headers and all that. I've got all that working. My question is specifically about what I need to do to my Swift classes to get them to show up in Obj-C code.

Take, for example, this simple class:

class MyClass { var value: String = "" } 

If I have this class in my Project, it doesn't get included in the MyProject-Swift.h file that gets auto-generated. My understanding is that in order to use a Swift class in Objective-C, my class needs to derive from a class that Objective-C knows about. This is where I start to doubt the actual requirements.

If my class were derived from a UIViewController, then no problem. But if this is just a model object, then it's not deriving from anything. While it is entirely possible to easily make my class derive from NSObject, and thus, it gets properly imported into the Obj-C code, deriving from NSObject can cause other issues down the road.

So if I don't want to make my class derive from NSObject, what can I do to make it visible to my Obj-C files? Is there a doc I just couldn't find that explains how to do this?

1 Answer 1

2

As far as I am aware currently, Only Swift classes that inherit from NSObject can be declared @objc and bridged into an Objective-C project.

Without that conformance/inheritance, you'll end up missing some crucial functionality to Objective-C like message sending.

All of that being said, an Objective-C class has to inherit from a parent class and the default root class is NSObject. You almost definitely want to just inherit and make your class a PONSO.

Sign up to request clarification or add additional context in comments.

2 Comments

Actually, you just have to inherit from NSObjectProtocol, (known as protocol NSObject in ObjC), not necessarily NSObject itself
Hmm, I was hoping there was a way to keep from having to inherit from NSObject and expose my class to the entire Objective-C runtime, considering that Swift methods run a lot faster because they don't have to deal with dynamic dispatch. My current issue is mainly with exposing a small singleton, though, so it might not be so bad. Also, as I port sections of the project from Obj-C to Swift, there's less and less interoperability support needed.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.