Home Explore Blog CI



nixpkgs

2nd chunk of `doc/languages-frameworks/swift.section.md`
49f5d833be5f85e8352a73cb8346bdba6555e2f6afc2cd740000000100000838
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: Packaging a SwiftPM Project with Nix
Summary
This section details how to package a SwiftPM project using Nix, involving generating Nix code with `swiftpm2nix`, creating a Nix expression to define the build process, fetching dependencies, configuring the build environment, and installing the resulting binaries. It also covers customizing the build with different configurations and flags, showcasing how to create a reproducible Swift build within Nixpkgs.