I need to make an library for iOS (either Framework or static library - I haven't decided yet) that can be used in both Objective-C and Swift projects. What is the best way of doing this? The way I see it I have three options:
- Write the library in Objective-C and add support for Swift (bridging headers etc).
- Write the library in Swift and add support for Objective-C.
- Write two libraries, both in Objective-C and Swift. I really want to avoid this option.
The main requirement here is that it should be as easy for developers to use as possible. Ideally, they should be able to choose their language and not care, or indeed even know, what language the library itself was written in. Can this be done?
Also, I want to be able to distribute the library with CocoaPods, if this has any significance.
Option 2. Is out of question (described in detail later)
Option 3. As you said, you should really avoid it.
Option 1 is the best. Just design your API with Obj-C and Swift in mind. What does it mean ?
• Don't use selectors - they're not a Swift standard.
• Use nullability to convert to optionals
• Closures and blocks may have the same syntax, but there's a slight difference, watch out for that:
Source: Apple's Using Swift with Cocoa and Objective-C - It explains everything in detail.
You can read more here.
When designing such API you have to know how everything is converted, but if you do it right the users won't notice a difference :)
Module File
Make sure your
x.framework
is shipped with themodules
folder and file inside.New Xcode generates it for you. This way users can use your Obj-C project in Swift without adding it to a bridging file. So they can just
import myLib
out of the box.Why not Swift?
Unfortunately, the most sensible way to distribute a compiled library right now is to write it in Objective-C.
And that's because of one big reason: Swift Binary Compatiblity Problem
Peter Steinberger, the founder of PSPDFKit, which is also a library distributed as a compiled library has ran into the same problem: they're stuck with Obj-C for now and can't use Swift.