Using Function pointer callback methods in Swift

Solution for Using Function pointer callback methods in Swift
is Given Below:

I’m seeking to better understand how imported C functions like this can be implemented in Swift. This error message is helpful, but I’ve tried many variations of this as params in the swift function and can’t quite get it.

Cannot convert value of type ‘() -> ()’ to expected argument type ‘method_handler?’ (aka ‘Optional<@convention(c) (Optional<UnsafeMutablePointer<msg_data>>, Optional<UnsafePointer>, Optional<UnsafeMutablePointer<Optional<UnsafeMutablePointer>>>, Int32, Optional) -> ()>’)

typedef void (*method_handler)(const msg_data_ptr msg, const char *types,
                                   arg_ptr *argv, int argc, void *user_data);
func handler(args)
{
    for (i, arg) in args.enumerated() {
        print("argument (i) is: (arg)")
    }
}

passed in here:

add_handler_new("handler", &handler, nil, 0, 1);

As the error message says, you have to use @convention(c) in order to define the swift function or closure that is interoperable with other C functions. Try this:

typealias MethodHandler = @convention(c) (
        _ msg_data_ptr : UnsafeMutablePointer<msg_data>?, 
        _ types: UnsafePointer<Int8>?, 
        _ argv : UnsafeMutablePointer<UnsafeMutablePointer<Int8>?>?, 
        _ argc: Int32, 
        _ user_data: UnsafeMutablePointer<Int8>?
    ) -> Void


let handler: MethodHandler = { msg_data_ptr, types, argv, argc, user_data in
    ...
}

add_handler_new("handler", handler, nil, 0, 1)