CodenameOne icon indicating copy to clipboard operation
CodenameOne copied to clipboard

RFE: Support for Swift libraries?

Open jsfan3 opened this issue 5 years ago • 2 comments

The fact that Codename One allows to create native interfaces with Objective-C is essential, but now all new libraries for iOS are written in Swift. This is starting to be a serious problem.

jsfan3 avatar Sep 27 '20 07:09 jsfan3

I agree. We should add support for Swift inside the native/ios directory.

Until that happens, you can use Swift libraries by creating a Swift framework and placing it in your native/ios directory zipped. E.g.

native/ios/MyFramework.framework.zip

Then you can call your framework's methods from Objective-C code using the usual Objective-C -> Swift interop mechanism.

You'll also need to add the following build hints:

ios.pods.build.CLANG_ALLOW_NON_MODULAR_INCLUDES_IN_FRAMEWORK_MODULES=YES
ios.pods.build.CLANG_ENABLE_MODULES=YES

If the Swift libraries you want to use are already set up to be usable from Objective-C (e.g. they've exported functions with @ObjC annotations), then you don't necessarily even need to create your own intermediary framework.. you can use them directly from your Objective-C code.

The webrtc cn1lib uses this approach because it uses a Swift library for some of the WebRTC stuff.

Improving Swift Integration

There are 2 levels of Swift integration that we could aim for to make things easier:

  1. The build server automatically packages .swift files as a framework so that you can place .swift files directly inside the native/ios directory. You still need an Objective-C file as the main native interface implementation, but can call the Swift classes from there.
  2. Remove the requirement of Objective-C entirely. Native interface can be defined purely in Swift. This would basically work by using the same technique as in "1" above, but the server would just automatically generate the needed bridging stubs so that the Swift native interface could work.

shannah avatar Sep 28 '20 11:09 shannah

Thank you for this guide.

Is there a way to use native Swift code in the native/ios directory instead of Objective-C?

schreiby avatar May 12 '22 18:05 schreiby