swiftlang/swift-java

Add support for escaping Swift closures

madsodgaard opened this issue · 1 comments

Right now, the JNI and FFM modes only support importing non-escaping closures. We should investigate and add support for escaping closures as well, as they are quite common in Swift, such as callbacks. We need to figure out a way to know when to "release" the closure, for example using some sort of wrapper object.

In JNI land this may mean something like this:

  • we may not be able to extract an @escaping () -> () safely since we need to keep the java callback object alive as long as the Swift closure is "escaped" and still alive
  • in JNI we need to DeleteGlobalRef once the closure was dropped
  • the solution could be to suggest wrapping the () -> () parameter (that a Swift func accepts) with a SwiftKitClosure<Void, Void> that does the DeleteGlobalRef when deinit is called on the class

Yes users would have to adopt this via an extension in Swift rather than "closures just work" which but at least it should be safe.