Keep Resources With The Swift Package That Owns Them

You move a helper into a Swift package. Its JSON file appears in the project navigator, the package compiles, and the consuming app launches. Then the help page is missing.

The build is green. The help screen did not get the memo.

A common cause is resource ownership: the helper still asks Bundle.main for a file that now belongs to a package target. An even less obvious failure happens when the app contains a different file with the same name. The lookup succeeds and returns the wrong content.

We’ll give a small source package its own JSON resource, expose a typed loading API, and test it with deliberately conflicting files.

Why check this now?

Swift’s November 11 update highlights the approaching CocoaPods transition. The CocoaPods plan schedules trunk to stop accepting new pods and versions on December 2, 2026. Existing published versions remain available; this isn’t a date when every existing CocoaPods build suddenly fails.

If that prompts a move to SwiftPM, migrating source is only part of the job. This article covers resource ownership for a source library you control. It does not replace a third-party vendor’s migration instructions or describe how to repackage a binary framework.

The underlying API is established. A Stack Overflow question about missing package JSON already has an accepted answer pointing to Bundle.module. We’ll take that answer through the consumer boundary and verify what actually ships.

Declare the resource on its owning target

Create this layout inside a HelpContent folder:

HelpContent/
├── Package.swift
├── Sources/HelpContent/
│   ├── HelpLibrary.swift
│   └── Resources/welcome.json
└── Tests/HelpContentTests/
    ├── HelpContentTests.swift
    └── Fixtures/welcome.json

Use this complete Package.swift:

// swift-tools-version: 6.2
import PackageDescription

let package = Package(
    name: "HelpContent",
    platforms: [.iOS(.v15), .macOS(.v12)],
    products: [
        .library(name: "HelpContent", targets: ["HelpContent"])
    ],
    targets: [
        .target(
            name: "HelpContent",
            resources: [.process("Resources")]
        ),
        .testTarget(
            name: "HelpContentTests",
            dependencies: ["HelpContent"],
            resources: [.process("Fixtures")]
        )
    ]
)

Resource support dates to Swift tools 5.3. This example chooses tools 6.2, iOS 15 and macOS 12 as its baseline and uses current Swift concurrency annotations. Verification used Xcode 27.2 / Swift 6.4.2; the tools declaration does not install that compiler.

Apple’s resource documentation scopes resources to a target. The two manifest paths above are relative to different target directories. The library’s resource and the test fixture will belong to different generated bundles, even though both are named welcome.json.

Put this in Sources/HelpContent/Resources/welcome.json:

{
  "title": "Welcome from the package",
  "body": "Your help content travels with the library."
}

For this flat JSON file, .process("Resources") is sufficient. If you need a directory hierarchy to survive unchanged, such as HTML with relative asset links, use an appropriate .copy rule instead. A processed folder is not a promise that its source layout survives. SwiftPM’s resource rules describe that distinction.

Keep the lookup inside the package

Put this in Sources/HelpContent/HelpLibrary.swift:

import Foundation

public nonisolated struct HelpPage: Decodable, Equatable, Sendable {
    public let title: String
    public let body: String
}

public nonisolated enum HelpContentError: Error, Equatable {
    case missingResource(String)
}

public nonisolated enum HelpLibrary {
    public static func welcome() throws -> HelpPage {
        try loadPage(named: "welcome", in: .module)
    }

    static func loadPage(named name: String, in bundle: Bundle) throws -> HelpPage {
        guard let url = bundle.url(forResource: name, withExtension: "json") else {
            throw HelpContentError.missingResource(name)
        }
        let data = try Data(contentsOf: url)
        return try JSONDecoder().decode(HelpPage.self, from: data)
    }
}

Bundle.module is generated for the resource-bearing target. It isn’t a universal bundle that searches every imported package. A different target’s accessor refers to that target’s resources.

Keith Harrison’s resource guide explains the declaration rules and exposing access outside the module. Here the public boundary is a HelpPage, so consumers don’t need the bundle name, filename, directory layout or decoder. loadPage(named:in:) remains internal so tests can exercise failures with their own fixtures.

The explicit nonisolated declarations make this small, immutable API usable with MainActor default isolation too. Loading is still synchronous: it reads and decodes a small bundled file. Load it once at a sensible ownership boundary rather than on every SwiftUI body evaluation. A large catalog needs a separate loading strategy.

From a consuming target that links the HelpContent product:

import HelpContent

let page = try HelpLibrary.welcome()
print(page.title)

In Xcode, add the local HelpContent package and select that product for the app target. Keep its source files and JSON in the package; don’t also add them individually to the app’s compile or resource phases. If you’re replacing an existing app-owned copy, remove that copy after updating its callers and verifying the consuming build.

There is no need for the consumer to reach into Bundle.module or guess a generated .bundle filename. Apple’s package-resources session recommends specific typed accessors when other modules need a resource. The generated bundle stays an implementation detail.

Make a same-name fixture prove ownership

Put a different document in Tests/HelpContentTests/Fixtures/welcome.json, with title Test fixture and body This belongs to the test target. Use the same two JSON keys as the library file.

Then put this in Tests/HelpContentTests/HelpContentTests.swift:

import Foundation
import Testing
@testable import HelpContent

@Test
nonisolated func packageOwnsItsWelcomePage() throws {
    let page = try HelpLibrary.welcome()
    #expect(page.title == "Welcome from the package")
    #expect(page.body == "Your help content travels with the library.")

    let fixture = try HelpLibrary.loadPage(named: "welcome", in: .module)
    #expect(fixture.title == "Test fixture")
    #expect(fixture != page)
}

The first call executes the library’s lookup. The explicit .module in the second call belongs to the test target. Reading both files and checking their different contents proves more than checking that some URL exists.

@testable allows the test to call the internal loader; it does not turn the library’s resource accessor into the test target’s accessor. The Stack Overflow discussion of SwiftPM test resources already covers declaring fixtures. The extra check here is that a fixture cannot accidentally stand in for the product’s actual content.

Run swift test from the package folder. Keep a consumer check as well: a unit test bundle is not the app you ship.

Check the built consumer, including failure

The standalone sample includes the package above, an executable consumer, a small iOS host and a Python 3 verification runner. The host app deliberately includes its own welcome.json with different content. It verifies that Bundle.main reads that decoy while HelpLibrary.welcome() still returns the package’s page.

The checks cover:

CheckWhat it establishes
Library and test target contain the same filenameEach target reads its own content
Host app contains the same filenameThe public API does not accidentally read the host’s copy
Missing individual file, malformed JSON, wrong field typeErrors remain errors instead of becoming an empty help page
Release consumer moved with its resource bundleLoading does not depend on the source checkout’s layout
Resource bundle removed from that isolated consumerThe check detects a broken distribution, rather than finding a hidden fallback

The optional URL guard handles a missing file in a bundle. It cannot make an entirely missing package resource bundle recoverable: the generated accessor in this toolchain traps if it cannot locate its bundle, before the loader reaches that guard. The sample’s deliberately broken distribution is tested in a separate process for that reason. Keep resource packaging as a release check.

Run python3 verify.py from the extracted sample for package tests and executable checks. Run python3 verify.py --ios separately for the native host; it requires the installed iOS 27.2 Simulator runtime. The final examples pass in ordinary and MainActor default isolation. Native execution uses iOS 27.2 Simulator; iOS 15 is a deployment target, not a claim of older-device testing. The sample also checks a Release consumer. It does not claim App Store archive/signing, previews, localization or binary-framework coverage.

Our package reproducibility article covers dependency resolution and toolchain inputs. This is the next boundary: after the right code builds, the right resource still needs to arrive with it.