Home Explore Blog Models CI



nixpkgs

2nd chunk of `doc/languages-frameworks/swift.section.md`
d32a15a0cd5aec5cd31833b89df2eabcdc29aa9c178e4aa80000000100000834
dependencies for you, when you need to write a Nix expression to package your
application.

The first step is to run the generator:

```sh
cd /path/to/my/project
# Enter a Nix shell with the required tools.
nix-shell -p swift swiftpm swiftpm2nix
# First, make sure the workspace is up-to-date.
swift package resolve
# Now generate the Nix code.
swiftpm2nix
```

This produces some files in a directory `nix`, which will be part of your Nix
expression. The next step is to write that expression:

```nix
{
  stdenv,
  swift,
  swiftpm,
  swiftpm2nix,
  fetchFromGitHub,
}:

let
  # Pass the generated files to the helper.
  generated = swiftpm2nix.helpers ./nix;

in
stdenv.mkDerivation (finalAttrs: {
  pname = "myproject";
  version = "0.0.0";

  src = fetchFromGitHub {
    owner = "nixos";
    repo = "myproject";
    tag = finalAttrs.version;
    hash = "";
  };

  # Including SwiftPM as a nativeBuildInput provides a buildPhase for you.
  # This by default performs a release build using SwiftPM, essentially:
  #   swift build -c release
  nativeBuildInputs = [
    swift
    swiftpm
  ];

  # The helper provides a configure snippet that will prepare all dependencies
  # in the correct place, where SwiftPM expects them.
  configurePhase = ''
    runHook preConfigure

    ${generated.configure}

    runHook postConfigure
  '';

  installPhase = ''
    runHook preInstall

    # This is a special function that invokes swiftpm to find the location
    # of the binaries it produced.
    binPath="$(swiftpmBinPath)"
    # Now perform any installation steps.
    mkdir -p $out/bin
    cp $binPath/myproject $out/bin/

    runHook postInstall
  '';
})
```

### Custom build flags {#ssec-swiftpm-custom-build-flags}

If you'd like to build a different configuration than `release`:

```nix
{ swiftpmBuildConfig = "debug"; }
```

It is also possible to provide additional flags to `swift build`:

```nix
{ swiftpmFlags = [ "--disable-dead-strip" ]; }
```

The default `buildPhase` already passes `-j` for parallel building.

If these two customization options are insufficient, provide your own

Title: SwiftPM Packaging: Nix Expression and Build Customization
Summary
This chunk details how to write a Nix expression for packaging Swift applications after `swiftpm2nix` has generated dependency files. It outlines the structure of the `stdenv.mkDerivation`, showing how to integrate `swiftpm2nix.helpers` for dependency configuration in the `configurePhase` and how to use `swiftpmBinPath` to locate and install compiled binaries in the `installPhase`. The `nativeBuildInputs` automatically trigger a default SwiftPM release build. Additionally, it explains how to customize the build process by setting `swiftpmBuildConfig` (e.g., to "debug") or by providing extra `swiftpmFlags` to the `swift build` command.