Swift Packages: exclude developments resources/assets from package used in archived app

When using Swift Packages in Xcode, is there a way to exclude files conditionally (like using DEBUG or similar)? I know I can exclude files but I want them while in development, but not in production.

I have a package that contains developments resource/assets (used to seed a Core Data database for the simulator + for Previews, with images and files), but I don't want to include these files in the package used by the real app when archiving.

Can we achieve that?

1 Like

One workaround is to rely on environment variables in your Package.swift

You can then do something like this

// swift-tools-version:5.7
// The swift-tools-version declares the minimum version of Swift required to build this package.

import Foundation
import PackageDescription

let mocksEnabled = ProcessInfo.processInfo.environment["MOCKS"] != "NO"

let package = Package(
    name: "MyPackage",
    defaultLocalization: "en",
    dependencies: [
    ],
    targets: [
      // your targets
    ]
)


package.targets.forEach { target in
    guard target.type == .regular else { return }

    var settings = target.swiftSettings ?? []

    if mocksEnabled || target.type == .test {
        settings.append(.define("MOCKS"))
    } else {
        target.exclude.append("Mocks")
    }

    target.swiftSettings = settings
}

We are using this to include mocks by default
They are by convention required to be located in a folder named Mocks at the root of each target.

On CI we then define a env var MOCKS=NO to exclude them.

One caveat though when using Xcode is you need to have the environment variable set BEFORE you launch Xcode.

So when you have to quit xcode (command + Q) and then launch it with the env vars set

For instance MOCKS=NO xed .

But as i said this is more of a workaround and i would really like a proper way to do these configurations

1 Like

An alternative approach, which will leave a bunch of empty files in your shipped project, but also hide the code, is to wrap the code in
if DEBUG

#endif

Curious to know if there are any changes to this? I have a bunch of CSV files that are used for Previews in many different packages (Features), but I want to exclude them from release builds.