Detect if Bundle.module is available

It’s great to have SPM managing resources and localization!

I would still like to have my library available with other dependencies managers (can I mention CocoaPods here?), so I would need to detect if Bundle.module is available at compile time. Otherwise, I’ll just get an error like this:

Type 'Bundle' has no member 'module'

Is there something like if @available(SPM), or if Bundle.hasMember(.module)? Any other solution?
I've found a solution for this. But this is just a workaround, so you should only use this until someone can find an official way to resolve this.

Code Block Swift
import class Foundation.Bundle
private class BundleFinder {}
extension Foundation.Bundle {
/// Returns the resource bundle associated with the current Swift module.
static var current: Bundle = {
// This is your `target.path` (located in your `Package.swift`) by replacing all the `/` by the `_`.
let bundleName = "AAA_BBB"
let candidates = [
// Bundle should be present here when the package is linked into an App.
Bundle.main.resourceURL,
// Bundle should be present here when the package is linked into a framework.
Bundle(for: BundleFinder.self).resourceURL,
// For command-line tools.
Bundle.main.bundleURL,
]
for candidate in candidates {
let bundlePath = candidate?.appendingPathComponent(bundleName + ".bundle")
if let bundle = bundlePath.flatMap(Bundle.init(url:)) {
return bundle
}
}
return Bundle(for: BundleFinder.self)
}()
}


I found you can use
Code Block Swift
#if SWIFT_PACKAGE
let resourceBundle = Bundle.module
#endif


This define is present when building the code via SwiftPM.

In the Package.swift in target declare:

Code Block
let package = Package(
  name: "Library",
  defaultLocalization: "en",
  platforms: [
    .iOS(.v11)
  ],
  products: [
    .library(
      name: "Library",
      targets: ["Library"]
    ),
  ],
  dependencies: [],
  targets: [
    .target(
      name: "Library",
      dependencies: [],
      path: "Sources",
      swiftSettings: [
        .define("SPM")
      ]
    ),
  ]
)


the important part is the definition of SPM, then we create the following extension

Code Block
#if !SPM
extension Bundle {
  static var module:Bundle { Bundle(identifier: "com.library.example")! }
}
#endif


this way we always have
Code Block
Bundle.module
available


Detect if Bundle.module is available
 
 
Q