How to run build phase Swift scripts in Xcode

Scott
2 min readNov 4, 2023

Credit to AF Swift Tutorials

  1. Create a new project

2. Add a new build phase

3. Add a target,

It should add a folder with a swift file called main in it.

4. Now make sure your project has the following script and setup:

xcrun --sdk macosx swiftc -parse-as-library ScriptTarget/main.swift -o ScriptTargetOutput
./ScriptTargetOutput

I accidentally added the build phase script to the command line target once. Be careful not to do that.

This is what my script looked like:

//
// main.swift
// ScriptTarget
//
// Created by Scott Lydon on 11/4/23.
//

import Foundation

@main
struct HelloXcode {
static func main() {
print("We did it!")
}
}

Here is the output in the build logs.

Importing Swift Packages in a custom build script

This can be tricky.

We need the package to be built before the script runs. The script runs before the main project builds. So we need to set the script target as a dependency to the main project target.

--

--