Mike Nathas Mike Nathas - 1 year ago 53
Swift Question

Converting Objective-C / C callback code to Swift

I'm currently converting some older Objective-C code to Swift and I'm stuck at some C stuff.

I do have an internal API which expects a callback function.

DoSomethingWithCallback(myCallbackType callback);

The callback type is specified

typedef void(*myCallbackType)(struct customStruct *);

In my Objective-C / C code I just added a

static void functionThatActsAsCallback(struct customStruct *myStruct) {

and could call everything with a


I've tried to convert this to Swift by creating the the callback function

func functionThatActsAsCallback(myStruct: UnsafePointer<customStruct>) -> Void {


and tried to do the call via


which results in an error

Cannot convert value of type '(UnsafePointer) -> Void' to argument type 'myCallbackType!'

I'm not quite sure why this error occurs and how to fix this.

Thanks in advance for any hint

Answer Source

You should check how your types and functions are imported into Swift, before using them.

If you have all types and functions declared in a single .h file:

  • Wait for Xcode to successfully index your project. (You may need to comment out error lines.)

  • Open the .h file in Xcode editor.

  • Click four square icon at the top left of the editor pane and choose "Generated Interface".

I could have gotten this with my sample project:

public typealias myCallbackType = @convention(c) (UnsafeMutablePointer<customStruct>) -> Void

public func DoSomethingWithCallback(callback: myCallbackType!)

(You may find this with Cmd-clicking on the imported type name or function name.)

So, your issue is caused by type mismatching with UnsafePointer and UnsafeMutablePointer. Modify your callback function as:

func functionThatActsAsCallback(myStruct: UnsafeMutablePointer<customStruct>) -> Void {


And call the DoSomethingWithCallback function as:


(Match letter cases.)

Defining your closure with:

let functionThatActsAsCallback: myCallbackType = {myStruct->Void in


helps you find the parameter type inferred by Swift.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download