Dan
Dan

Reputation: 2344

Using an Objective-C typedef void in Swift

I am using an Objective-C API in a new Swift environment. For the most part everything is working great but I'm getting stuck on a typedef issue.

The API has a typedef defined as:

typedef void* TESTHANDLE;

Usually in Objective-C I'd simply use this like declaring any kind of variable:

TESTHANDLE NewTestHandle;

The image below is an example from an Objective-C project that uses this.

enter image description here

I want to declare a new TESTHANDLE variable in Swift, the same way I do above. I need to assign a value to TestHandle later in the code, which is of type TESTHANDLE.

enter image description here

Reading up on this over I see that typealias is now the way to go BUT I can't change the API.

How can I use this typedef from Objective-C in Swift?

Upvotes: 0

Views: 794

Answers (1)

Ayan Sengupta
Ayan Sengupta

Reputation: 5386

You can do it by simply adding a bridging header to your project.

Taking example of the following Objective C class:

enter image description here

  1. Add a header file to your project. The default naming convention is -Bridging-Header.h

  2. Import your Objective-C API headers to this header using #import statement.

enter image description here

  1. Under project Build Setting set this header as the briddge between your Objective-C and Swift world by putting the path of it in "Objective-C Bridging Header". Relative paths to your .xcodeproj will simply work.

enter image description here

  1. Use the type in Swift as usual

enter image description here

However keep in mind that all such types will be treated as UnsafeRawPointer or UnsafeMutableRawPointer in Swift.

Upvotes: 2

Related Questions