Function pointer with generic parameters

I am trying to create a function that has a function pointer with generic parameter but without any success.


I have following code


func connect<T>(object: UnsafeMutablePointer<T>, handler: @convention(c) UnsafeMutablePointer<T> -> Void) {

}


But when I try to compile it I get an error: @convention(c) type is not representable in Objective-C


If I change a type to UnsafeMutablePointer<Void> -> Void then it works but then I lose safety of generics. I don't see a reason why it cannot be represented in ObjC? Because in ObjC it can be represented with Void while keeping safety in Swift.


Is there any workaround or do you know why it doesn't work?

Basically, certain things from Swift will prevent methods and functions from being able to be called from objective-C. Swift generics are one of those things.


"For example, a method that takes a generic type as an argument or returns a tuple will not be usable from Objective-C."


So your callback handler can't be called from obj-C or C, except by using UnsafeMutablePointer<Void> or UnsafePointer<Void> since those types are explicitly bridged into types that will work with obj-c / c.



https://developer.apple.com/library/prerelease/ios/documentation/Swift/Conceptual/BuildingCocoaApps/MixandMatch.html#//apple_ref/doc/uid/TP40014216-CH10-ID136


https://developer.apple.com/library/prerelease/ios/documentation/Swift/Conceptual/BuildingCocoaApps/InteractingWithCAPIs.html

But as you said the parameter could be bridged with Void, why don't they do it?

I think this works, but I'm not sure it gives you what you are looking for.


func foo<T>(object: UnsafeMutablePointer<T>,
            handler: @convention(c) UnsafeMutablePointer<Void> -> Void) {
     // ...
     handler(object)
     // ...
}

Basically, what you'd be doing is implicitly overloading based on calling convention. It would be nice if you could do this manually, but it currently isn't possible. Ideally, you'd have the generic one you're showing without the @convention(c), and then overload it for T == Void and with the @convention(c), with the overload just calling into the generic version, wrapping the @convention(c) function value in a closure. However, this isn't possible unless you have some T != Void which you can trivially map the object and the function value into, since otherwise you wouldn't be able to call up.

Function pointer with generic parameters
 
 
Q