How to create method to access Swift Package bundle files

I am creating my first Swift package. I use Resource files for unit testing. I have code that correctly loads a file within a unit test. That works fine. How do I create a Bundle extension, or other method, so I don’t need to copy this code for every unit test file load?

What I did to load Resources in my unit tests:

  • Created a “Resource” directory under my Test target.
  • Added the Resources to my Package.swift file, under the Test target
  • Use Bundle.module to access the resources in my unit test.

My unit test code:

  func testLoadResourceFromFile() throws {

    let fileName = "myFile.csv"
    guard let fileURL = Bundle.module.url(
      forResource: fileName,
      withExtension: nil) else {
      fatalError("Unable to find bundle file \(fileName)")
    }

    guard let csvString = try? String(contentsOf: fileURL) else {
      fatalError("Unable to load bundle file \(fileName)")
    }

    // csvString now hols string for Resource file

I’ve attempted to create a method using Bundle extension and global method. Both give compile errors:

xtension Bundle {
 // compile error:
  public static var bundleModule: Bundle = .module
  ...

  // try2
  public func stringFromPackageBundleFile(_ fileName: String) -> String {
    // compile error
    guard let fileURL = Bundle.module.url(
      forResource: fileName,
      withExtension: nil) else {
      fatalError("Failed to locate \(fileName) in package bundle.")
    }

How do I create a method to reuse the working code? Is there an issue in that the working code is running in the unit test context, but the methods I am trying to write are being compiled in the app context?

I was able to figure this one out myself. I had created a “Bundle.swift” file with the global method stringFromPackageBundleFile(). This file was in the “PackageName” file hierarchy. Wen I moved the file to the “PackageTestName” hierarchy, it compiled just fine.

There is no “Target Membership” in the File Inspector when creating packages. The file belongs to the target based only on the location of the file. I didn’t know that. Once I learned, moving the file fixed my issue….

Leave a Comment