# 3 · Types & Functional Programming Swift's type system and its functional tools are exactly the parts that make Lyrebird pleasant. Instead of hand-wiring twelve oscillators, you *describe* twelve oscillators and let Swift build them. This guide connects Swift's types and functional style directly to synthesis. --- ## Part 1 — Swift's type system, the parts that matter here ### Type annotations — write them, especially here Guide 2 made the case; this guide is where it pays off. Swift *can* infer a binding's type, so both of these compile: ```swift let freq = 440.0 // inferred Double — works, but don't let freq: Double = 440.0 // annotated — do this ``` **Always annotate.** Two reasons, and both bite harder in this guide's territory: - **Clarity.** The expressions you're about to build — `carrier * tremolo`, `voices.reduce(0.0) { $0 + $1 }`, chained `map`/`filter` — produce types that aren't obvious at a glance (`BinaryOpGenerator`, `GeneratorArray`, `any ValidGeneratorInput`). The annotation tells the reader exactly what they're holding. - **Compile speed.** Swift's type inference is *most* expensive on exactly these long, generic, operator-heavy graph expressions. Annotating the binding short-circuits the inference work. One file won't matter; a large project full of synth graphs will feel the difference, and so will the Xcode editor. Every example below is annotated. The only spots left un-annotated are the three where Swift's grammar forbids it — **closure parameters** (`{ x in … }`), **tuple destructures** (`let (a, b) = pair`), and **pattern bindings** (`case let .hz(f)`) — all of which appear in this guide and are flagged where they do. ### Enums — a fixed set of named choices An `enum` is one of a closed list of cases. Perfect for a mode, a waveform choice, a rate: ```swift enum Waveform { case sine, saw, square, triangle } func makeOsc(_ w: Waveform, freq: Double) -> any AudioGenerator { switch w { case .sine: return OscSin.Audio(freq: freq) case .saw: return OscSawtooth.Audio(freq: freq) case .square: return OscSquare.Audio(freq: freq) case .triangle: return OscTriangle.Audio(freq: freq) } } ``` The compiler forces the `switch` to handle every case — add a new waveform and it *tells* you every place that needs updating. That's the safety enums buy. Lyrebird uses them widely (rate kinds, distribution kinds, error kinds). Enums can carry values, too: ```swift enum Pitch { case hz(Double) // raw frequency case midi(Int) // MIDI note number } func frequency(of p: Pitch) -> Double { switch p { case .hz(let f): return f case .midi(let n): return 440.0 * pow(2.0, Double(n - 69) / 12.0) } } frequency(of: .midi(69)) // 440.0 frequency(of: .hz(500.0)) // 500.0 ``` ### Protocols — "any type that can do X" A **protocol** is a contract: a set of capabilities a type promises to provide. This is the backbone of Lyrebird's design. You've already used several without naming them: - `Generator` — anything that produces samples (oscillators, filters, effects). - `AudioGenerator` / `ControlGenerator` — generators that run at audio rate vs. control (block) rate. - `ValidGeneratorInput` — anything you can pass as a generator's input. That last one is why you can write **any** of these as a `freq:` argument: ```swift OscSin.Audio(freq: 440.0) // a Double is a ValidGeneratorInput OscSin.Audio(freq: 440) // an Int is too OscSin.Audio(freq: someOtherOscillator) // a Generator is too — that's FM! ``` `freq:` accepts `any ValidGeneratorInput`. A literal number gives a fixed frequency; passing another generator means that generator *modulates* the frequency. One protocol, three behaviors, no overloads to memorize. The keyword `any` (as in `any AudioGenerator`, `any ValidGeneratorInput`) means "some value whose exact type I don't need to name, as long as it satisfies this protocol." You'll type it often. ### Operator overloading — audio math reads like math Lyrebird defines `+ - * /` on generators, so signal processing looks like arithmetic: ```swift let carrier: OscSin.Audio = OscSin.Audio(freq: 440.0) let tremolo: OscSin.Audio = OscSin.Audio(freq: 5.0, mul: 0.5, add: 0.5) // 5 Hz, range 0…1 let wobbled: BinaryOpGenerator = carrier * tremolo // amplitude modulation let mixed: BinaryOpGenerator = wobbled + noiseLayer // sum two signals ``` Note the annotations: `carrier * tremolo` and `wobbled + noiseLayer` both produce a `BinaryOpGenerator` — the type Lyrebird's overloaded `*` and `+` return. Writing it out means you (and the compiler) don't have to work it out. `carrier * tremolo` isn't multiplying two numbers — it builds a new generator that multiplies the two signals sample by sample. The result is itself a `Generator`, so you keep composing. This is the single most Swift-flavored thing about Lyrebird, and it comes straight from operator overloading. --- ## Part 2 — Closures, the gateway to functional style A **closure** is a block of code you can pass around like a value — an anonymous function. Full form: ```swift let double: (Double) -> Double = { x in return x * 2.0 } double(21.0) // 42.0 ``` The binding's type is `(Double) -> Double` — "takes a Double, returns a Double." Because we annotated it, the closure's own parameter `x` is inferred (closure parameters are one of the three places you *can't* write an annotation). Swift lets you shrink closures aggressively. When the type is known from context, you can drop the parameter types, the `return`, and even name parameters positionally with `$0`, `$1`: ```swift // These are the same closure, progressively shortened: { (x: Double) -> Double in return x * 2.0 } { x in x * 2.0 } { $0 * 2.0 } ``` `$0` is "the first argument." This terse form is everywhere in Swift and in Lyrebird — you saw it already: ```swift let oscs: GeneratorArray = expand([440.0, 880.0]) { OscSin.Audio(freq: $0) } // └── a closure: "given a frequency $0, make an oscillator" ``` When a closure is the **last** argument, it moves outside the parentheses (trailing-closure syntax) — that's why `expand([...]) { … }` has the braces hanging off the end. --- ## Part 3 — `map`, `filter`, `reduce` on collections These three functions replace most `for` loops in idiomatic Swift, and they shine when generating synthesis material. ### `map` — transform every element ```swift let midiNotes: [Int] = [60, 64, 67, 71] // a Cmaj7 chord let freqs: [Double] = midiNotes.map { midiToHz($0) } // → [261.6, 329.6, 392.0, 493.9] ``` `map` runs the closure on each element and collects the results into a new array. No loop, no mutable accumulator, no index bookkeeping. ### `filter` — keep the elements that pass a test ```swift let audible: [Double] = freqs.filter { $0 < 20000.0 } // drop anything above hearing ``` ### `reduce` — combine everything into one value ```swift let total: Double = freqs.reduce(0.0) { $0 + $1 } // sum // or the shorthand: let total2: Double = freqs.reduce(0.0, +) ``` `reduce` starts from an initial value (`0.0`) and folds each element in. `$0` is the running result, `$1` the current element. ### Chaining them ```swift let detuned: [Double] = midiNotes .map { midiToHz($0) } // notes → frequencies .map { $0 * 1.003 } // detune each up ~5 cents .filter { $0 < 8000.0 } // drop the highest partials ``` Each step is a small, obvious transformation. Read top to bottom, it's a pipeline. --- ## Part 4 — Putting it together in a Synthesizer Here's where functional style pays off. A chord synthesizer, built from an array of MIDI notes — no matter how many notes, the code is the same length: ```swift final class Chord: SynthesizerBase { // The notes to play. Change this array; the graph adapts. let notes: [Int] = [60, 64, 67, 71] // Cmaj7 override func build() { // 1. Notes → frequencies (map). let freqs: [Double] = notes.map { midiToHz($0) } // 2. Frequencies → oscillators, one per note. Quieter as the chord grows. let level: Double = 0.2 / Double(freqs.count) let voices: [OscSin.Audio] = freqs.map { OscSin.Audio(freq: $0, mul: level) } // 3. Sum all voices to a single mono signal (reduce, starting from silence). let mix: any ValidGeneratorInput = voices.reduce(0.0) { $0 + $1 } // 4. Center it and send to output. output(bus: 0, source: Pan2(input: mix, pan: 0.0)) } // MIDI note number → frequency in Hz. func midiToHz(_ note: Int) -> Double { return 440.0 * pow(2.0, Double(note - 69) / 12.0) } } ``` Read step 3 carefully: `voices.reduce(0.0) { $0 + $1 }` starts from the scalar `0.0` and adds each oscillator in turn using Lyrebird's overloaded `+`. The result is a generator that sums the whole chord. Add a note to `notes` and everything downstream just works. ### Multichannel with `expand` If instead of *mixing* the notes you want each on its **own output channel**, Lyrebird gives you `expand`, the generator-graph cousin of `map`: ```swift override func build() { let freqs: [Double] = notes.map { midiToHz($0) } // One generator per channel: channel 0 = first note, channel 1 = second, … let spread: GeneratorArray = expand(freqs) { OscSin.Audio(freq: $0, mul: 0.15) } output(bus: 0, source: spread) } ``` `expand(inputs) { factory }` is `map` for building a multichannel `GeneratorArray`: it applies the factory closure to each input and bundles the results into one channel-per-element generator. Same mental model as `map`, tuned for the audio graph. --- ## Part 5 — Value types keep synthesizers safe Recall from guide 2: `struct` is a value type, copied on assignment. Lyrebird leans on this. When the engine runs your synthesizer, it works with a **copy of the graph per instance** — no two playing voices share mutable state, which is what makes polyphony safe on the audio thread. You benefit by keeping your *own* data in `struct`s and `let`s. A little value type to bundle note parameters: ```swift struct VoiceSpec { let freq: Double let amp: Double let pan: Double } let specs: [VoiceSpec] = [ VoiceSpec(freq: 220.0, amp: 0.2, pan: -0.5), VoiceSpec(freq: 440.0, amp: 0.2, pan: 0.5), ] ``` Then drive the graph from data: ```swift override func build() { let voices: [any ValidGeneratorInput] = specs.map { spec in let osc: OscSin.Audio = OscSin.Audio(freq: spec.freq, mul: spec.amp) return Pan2(input: osc, pan: spec.pan) } // Two Pan2 outputs, each already stereo — sum them. let mix: any ValidGeneratorInput = voices.reduce(0.0) { $0 + $1 } output(bus: 0, source: mix) } ``` **Data describes the sound; `map` turns data into graph.** That separation — a plain array of specs, a functional transform into generators — is the pattern you'll reuse constantly. --- ## What you learned - Swift's **enums, protocols, and operator overloading** are the machinery behind Lyrebird's expressive API — `any ValidGeneratorInput`, `freq:` accepting a modulator, `a + b` mixing signals. - **Closures** (`{ $0 * 2 }`) and the **functional trio** (`map`, `filter`, `reduce`) let you generate synthesis material from data with no loops. - `expand` is `map` for building multichannel generators. - Keeping your parameters in **value types** mirrors how Lyrebird keeps voices independent. - **Annotating every binding** earns the most here: graph expressions have non-obvious types, and inference on them is the slowest thing you can ask the compiler to do. Next: [Xcode, Packages & Debugging](04-xcode-and-packages.md) — moving from single files to real projects: the IDE, adding Lyrebird as a package, Debug vs Release, and breakpoints.