# 4 · Xcode, Packages & Debugging So far you've run single `.swift` files. Real work happens in **projects**: multiple files, dependencies like Lyrebird, a build configuration, and a debugger. This guide covers the tools — Xcode and Swift Package Manager — plus how to add Lyrebird, how to set up Debug vs Release, and how to debug a running synth without breaking the audio. --- ## Part 1 — Two ways to build, and when to use each You have two toolchains, and they're two views of the *same* project: | | Swift Package Manager (CLI) | Xcode (IDE) | |---|---|---| | Invoked with | `swift build`, `swift run`, `swift test` | GUI: pick a scheme, press ▶ | | Best for | quick iteration, servers, CI, headless CLI synths | editing with autocomplete, the visual debugger, GUI/iOS apps | | Debugger | `lldb` on the command line | graphical breakpoints, variable inspector | They read the **same `Package.swift`**. Use the CLI for fast loops on a command-line piece; use Xcode when you want autocomplete, breakpoints you can click, or you're building a windowed/iOS app. Learn both — they complement each other. ### Installing Xcode Install **Xcode** from the Mac App Store (it's large — several GB). Launch it once so it finishes installing components. That also gives you the command-line tools (`swift`, `xcodebuild`, `lldb`). Lyrebird needs **Xcode 16+, macOS 15+**. Verify from Terminal: ```sh swift --version # expect Apple Swift version 6.0 xcode-select -p # should print a path, not an error ``` --- ## Part 2 — What a Swift package is A **Swift package** is a folder with a `Package.swift` manifest describing what to build and what it depends on. The manifest *is* Swift code: ```swift // swift-tools-version: 6.0 import PackageDescription let package = Package( name: "MyPiece", platforms: [.macOS(.v15)], dependencies: [ // Lyrebird, fetched from its git host: .package(url: "https://realizedsound.mooo.com/josh/Lyrebird", from: "1.0.0"), ], targets: [ .executableTarget( name: "MyPiece", dependencies: [ .product(name: "Lyrebird", package: "Lyrebird"), // add this line only if you use the GUI module: // .product(name: "LyrebirdUI", package: "Lyrebird"), ] ), ] ) ``` Key ideas: - **`dependencies`** lists packages you rely on. `from: "1.0.0"` means "1.0.0 or any compatible later version." SwiftPM downloads and pins them for you. - **`targets`** are the things *you* build. An `.executableTarget` produces a runnable program (it needs a `main.swift`); a `.testTarget` holds tests; a `.library` target is reusable code. - A target lists which **products** of a dependency it uses. Lyrebird vends `Lyrebird` (the core), `LyrebirdUI` (SwiftUI controls), and a few others. > One inconsistency you may notice: `let package = Package(…)` here has **no** type annotation, even though guide 2 told you to annotate everything. `Package.swift` is a manifest, and every Swift package — Lyrebird's included — writes that line un-annotated by convention. It's the one place to follow the crowd. In your actual *program* code (`main.swift`, your synthesizers), keep annotating. > **The naming quirk, one more time:** you depend on the product `Lyrebird`, but in your Swift files you write `import LyrebirdSynth`. Product name ≠ module name. This trips up everyone once; now it won't trip up you. ### The fastest way to scaffold: the `lyrebird` CLI Lyrebird ships a command-line tool that writes the whole package for you: ```sh lyrebird new MyPiece # creates MyPiece/ with Package.swift + main.swift cd MyPiece lyrebird run # build and play ``` That's the shortest path and it generates a correct `Package.swift`. See [`docs/tooling/cli-guide.md`](../tooling/cli-guide.md) for the full CLI. If you'd rather do it by hand, the manifest above is all you need. ### Using a local Lyrebird checkout If you've cloned Lyrebird next to your project (common while learning, so you can read the source), depend on it by **path** instead of URL: ```swift dependencies: [ .package(path: "../Lyrebird"), // relative to your Package.swift ], ``` This is exactly what the bundled demos do — look at `Demos/LyrebirdQuickstartDemo/Package.swift`. --- ## Part 3 — Opening and running in Xcode Two ways to open a package in Xcode: - **A package folder:** `File → Open…` and select the folder containing `Package.swift` (or run `xed .` from inside it in Terminal). Xcode reads the manifest, resolves dependencies, and you're ready. - **A workspace/project:** the Lyrebird demos ship a `Lyrebird.xcworkspace` — open *that*, not an individual `.xcodeproj`, so all demos share the one local package. Once open: 1. **Pick a scheme** in the toolbar (top, next to the ▶/■ buttons). A **scheme** says *what to run* — e.g. `MyPiece`, or `LyrebirdQuickstartDemo`. For a package, Xcode makes one scheme per executable/test target. 2. **Pick a destination** — "My Mac" for a macOS piece, or a connected iPhone / simulator for iOS. (iOS simulators produce no audio; use a real device for sound.) 3. **Press ▶ (Run)** or `⌘R`. Xcode builds and launches. Output appears in the **console** at the bottom. 4. **Press ■ (Stop)** or `⌘.` to end it. **Targets vs. schemes, briefly:** a *target* is a buildable unit defined in `Package.swift` (your executable, the test bundle). A *scheme* is a saved recipe for building and running one or more targets in a chosen configuration. You edit build behavior (including Debug vs Release, next) by editing the scheme. The CLI equivalents, for reference: ```sh swift build # compile (Debug by default) swift run # build + run swift test # run tests swift run -c release # build + run optimized (see below) ``` --- ## Part 4 — Debug vs Release configurations Every build uses a **configuration**. Two ship by default: | | **Debug** | **Release** | |---|---|---| | Optimization | none (`-Onone`) | full (`-O`) | | Speed | slow | fast (often 5–20× on DSP) | | Symbols / debug info | full | present, but code is reordered/inlined | | Safety checks | on | some elided | | Use for | editing, breakpoints, stepping | performance, real audio, shipping | ### Why this matters *a lot* for audio Lyrebird runs your generator graph on a real-time thread that must finish each 512-sample block before the deadline. **Debug builds are unoptimized and can be 10× slower** — heavy patches that run cleanly in Release will glitch, crackle, or drop out in Debug. Two consequences: - When something *sounds* wrong but *is* logically correct, **try a Release build before assuming a bug** — you may just be starved for CPU. - Any performance measurement in Debug is meaningless. Lyrebird's own benchmark docs say it outright: *"Always run with `-c release`; debug builds give meaningless numbers."* So: **debug logic in Debug, judge sound and speed in Release.** ### Switching configuration — command line ```sh swift run # Debug swift run -c release # Release swift build -c release # Release build only ``` ### Switching configuration — Xcode Xcode's ▶ Run button uses your scheme's **Run** action, which defaults to **Debug**. To change it: 1. Menu **Product → Scheme → Edit Scheme…** (or click the scheme name → *Edit Scheme…*). 2. Select the **Run** action in the left column. 3. On the **Info** tab, set **Build Configuration** to **Release** (or back to **Debug**). 4. Close. Now ▶ builds that configuration. A common workflow is to leave **Run = Debug** (so breakpoints and stepping work well) and switch to **Release** only when you want to hear the patch at full performance or profile it. The **Profile** action (`⌘I`, opens Instruments) already defaults to Release for exactly this reason. ### Per-target build settings If you need finer control (a custom optimization flag, a compilation condition), a SwiftPM target can carry settings in `Package.swift`: ```swift .executableTarget( name: "MyPiece", dependencies: [ .product(name: "Lyrebird", package: "Lyrebird") ], swiftSettings: [ // Example: define a flag you can check with #if in code. .define("VERBOSE_LOGGING", .when(configuration: .debug)), // Example: force optimization even in Debug for a hot target. .unsafeFlags(["-Ounchecked"], .when(configuration: .release)), ] ) ``` Then in code: ```swift #if VERBOSE_LOGGING print("Voice started at \(freq) Hz") // compiled in only for Debug #endif ``` `#if … #endif` is **conditional compilation** — the code inside only exists in builds where the flag is set. Great for debug-only logging that costs nothing in Release. (You'll also see `#if os(iOS)` / `#if os(macOS)` in Lyrebird for platform-specific code.) --- ## Part 5 — Breakpoints and debugging ### Setting a breakpoint In Xcode, click the **gutter** (the margin left of the line numbers) next to a line. A blue arrow appears — that's a breakpoint. Run in **Debug**; when execution reaches that line it **pauses**, and you can: - **Inspect variables** in the Variables View (bottom-left), or hover over a value in the editor. - **Step** with the toolbar: *Step Over* (`F6`, run this line), *Step Into* (`F7`, descend into the call), *Step Out* (`F8`, finish the current function), *Continue* (`⌃⌘Y`, resume). - **Evaluate expressions** in the console with `po` (print object) or `p`: ``` (lldb) po freqs (lldb) po engine.sampleRate (lldb) p 440.0 * 2 ``` ### Conditional and action breakpoints Right-click a breakpoint → **Edit Breakpoint…** to: - Add a **condition** — pause only when it's true, e.g. `note > 100`. Invaluable when a loop runs thousands of times and only one iteration is wrong. - Add an **action** like *Log Message* or *Debugger Command*, optionally with **"Automatically continue"** — so it logs without stopping. This is a print statement you can add/remove without editing and rebuilding. ### The audio-thread rule — do NOT breakpoint the render callback This is the one debugging pitfall unique to real-time audio, and it's important: > **Never set a breakpoint inside a Generator's `_computeSamples` / render path.** That code runs on the real-time audio thread. Pausing it freezes audio production entirely — the device underruns, you get a horrible glitch or silence, and the state you're inspecting is already unrepresentative. The same goes for `print` on that thread: allocating a `String` mid-render can itself cause a dropout. (This is why Lyrebird's rules forbid `print`, allocation, and locks on the RT thread.) Where you **can** freely breakpoint and print: your **setup and control code** — `build()`, `main.swift`, parameter changes, scheduling, anything that runs on the main thread before or between audio blocks. Break in `build()` to inspect the graph you're wiring; that's on the main thread and perfectly safe. ### Debugging what the audio thread is doing Since you can't stop the render thread, Lyrebird gives you non-blocking tools instead: - **`SynthesizerBase.debugTap`** — a per-instance, RT-safe tap for observing a live voice's output without breaking timing. See [`Sources/Lyrebird/Lyrebird.docc/Debugging.md`](../../Sources/Lyrebird/Lyrebird.docc/Debugging.md) for this and LLDB recipes for inspecting a live generator. - **`GeneratorBase.debugTag`** — label a generator so you can find it in the debugger. - The **message center** and **node-tree mirror** (`docs/diagnostics-guide.md`) surface what the engine is doing as inspectable, non-RT data. For ordinary Swift logic bugs — a wrong frequency table, an off-by-one in a pattern, an optional that's unexpectedly `nil` — regular breakpoints in your main-thread code are exactly the right tool. ### Crashes and the "force-unwrap" reminder If your program crashes with `Fatal error: Unexpectedly found nil while unwrapping an Optional`, you (or code you called) used `!` on a `nil` optional — the exact thing guide 2 warned against. The debugger stops on the offending line; read it, then replace the `!` with `if let` / `guard let` / `??`. In Lyrebird's own code this is a banned pattern precisely because on the audio thread that crash is a hard failure. --- ## Part 6 — A realistic workflow Putting the whole toolchain together, a typical loop while developing a piece: 1. **Edit** in Xcode (autocomplete, inline errors) — or your editor of choice. 2. **Run in Debug** (`⌘R`) to check logic; set breakpoints in `build()`/`main.swift` if something's off. 3. **Switch the scheme to Release** (or `swift run -c release`) to hear it perform and confirm it's not CPU-starved. 4. **Iterate.** For fast headless loops, `swift run` from Terminal beats a full IDE cycle. 5. **Test** with `swift test` if you've written any (Lyrebird uses Swift Testing — `@Test`, `#expect`). --- ## What you learned - A **Swift package** (`Package.swift`) declares dependencies and targets; add Lyrebird by URL or local path, then `import LyrebirdSynth`. - **Xcode** (schemes, destinations, ▶) and the **`swift` CLI** are two views of the same package — use each where it's strongest. - **Debug vs Release**: debug logic in Debug, judge sound and speed in Release; switch via *Edit Scheme → Run → Build Configuration* or `-c release`. Debug audio can glitch purely from being unoptimized. - **Breakpoints** are for your main-thread setup/control code. **Never** breakpoint or `print` on the render thread — use `debugTap`, `debugTag`, and the diagnostics tools instead. --- That's the series. You can now write Swift, understand Lyrebird's shape, use its expressive type-driven API, and build/run/debug real projects. From here, the [main documentation](../../README.md) — the generator catalog, the synthesizer protocol, routines and patterns — is open to you. Go make sound.