abc64df4d7
Documentation-only release. Adds docs/learning-swift/ — a four-part introduction to Swift for Lyrebird users coming from SuperCollider, Max/MSP, Csound, etc. (Hello World, Swift basics & best practices, types & functional programming, Xcode/packages/debugging). Linked from README.md and LYREBIRD_START_HERE.md. See RELEASES.md. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
277 lines
12 KiB
Markdown
277 lines
12 KiB
Markdown
# 2 · Swift Basics & Best Practices
|
|
|
|
Guide 1 showed a working program. This one slows down and teaches the pieces so you can write your own. Every concept is paired with a Lyrebird use so nothing feels abstract.
|
|
|
|
Keep a terminal open. You can test tiny snippets by putting them in a file and running `swift file.swift`, or in Xcode's REPL (`swift` with no arguments gives you an interactive prompt).
|
|
|
|
---
|
|
|
|
## Values, constants, and variables
|
|
|
|
```swift
|
|
let sampleRate: Int = 48000 // a constant — cannot be reassigned
|
|
var gain: Double = 0.5 // a variable — can change
|
|
gain = 0.7 // fine
|
|
// sampleRate = 44100 // ERROR: cannot assign to a 'let'
|
|
```
|
|
|
|
- **`let` is your default.** Reach for `var` only when a value genuinely changes. Constants are easier to reason about and the compiler catches accidental mutation. This isn't just style — Lyrebird's whole design leans on immutable, copy-per-instance graphs, and `let` reinforces that habit.
|
|
- **Write the type after the name** — the `: Int` / `: Double` above. That's a **type annotation**, and this series recommends it on *every* binding. Read the next section for why.
|
|
|
|
### Annotate your types — a best practice, not just a Lyrebird rule
|
|
|
|
Swift *can* infer a binding's type: `let sampleRate = 48000` compiles fine and `sampleRate` is an `Int`. But writing the type explicitly — `let sampleRate: Int = 48000` — is worth the few extra characters, for two concrete reasons:
|
|
|
|
1. **Clarity.** Swift is strongly typed; every value has exactly one type, and stating it means a reader (including future-you) never has to trace an expression to learn what they're holding. `let voices: [OscSin.Audio] = …` tells you at a glance.
|
|
2. **Compile speed.** When you leave the type off, the compiler must *infer* it — and Swift's type inference is expensive, especially for the long, generic, operator-heavy expressions you build with audio graphs (`osc1 * env + osc2 * 0.3`, chains of `map`/`reduce`). Annotating the binding short-circuits that work. On a single file you won't notice; **across a large project it adds up to real build-time savings**, and Xcode's editor feels snappier too.
|
|
|
|
So: **annotate every `let` and `var`.** Every example in this series does. The Lyrebird codebase *requires* it for exactly these reasons — you'll see it in all the source — and it's a good habit in any Swift project of size.
|
|
|
|
> The rule has a few grammar exceptions where Swift simply won't accept an annotation — closure parameters (`{ x in … }`), tuple destructures (`let (a, b) = pair`), and pattern bindings (`case let .hz(f)`). Guide 3 points them out as they come up. Everywhere else: annotate.
|
|
|
|
---
|
|
|
|
## The basic scalar types
|
|
|
|
| Type | What it is | Example | Lyrebird use |
|
|
|------|-----------|---------|--------------|
|
|
| `Int` | whole number | `512` | block size, channel counts, bus numbers |
|
|
| `Double` | 64-bit decimal | `440.0` | frequency, gain, pan, time in seconds |
|
|
| `Bool` | true / false | `true` | flags, toggles |
|
|
| `String` | text | `"hello"` | messages, file paths |
|
|
|
|
**Audio is almost always `Double` in Lyrebird.** Frequencies, amplitudes, pan positions, seconds — all `Double`. When you write `440.0` (with the decimal point) you get a `Double`; `440` alone is an `Int`. Mixing them is an error Swift makes you resolve explicitly:
|
|
|
|
```swift
|
|
let freq: Double = 440.0
|
|
let ratio: Int = 2 // Int
|
|
// let up = freq * ratio // ERROR: Double * Int
|
|
let up: Double = freq * Double(ratio) // convert first — OK, = 880.0
|
|
```
|
|
|
|
That strictness feels fussy at first and saves you from whole categories of bugs. Convert deliberately with `Double(...)`, `Int(...)`, etc.
|
|
|
|
---
|
|
|
|
## Strings and interpolation
|
|
|
|
```swift
|
|
let note: String = "A4"
|
|
let hz: Double = 440.0
|
|
print("Note \(note) is \(hz) Hz") // Note A4 is 440.0 Hz
|
|
```
|
|
|
|
`\(...)` drops any value into a string. Great for `print` debugging. (One caution you'll meet later: building strings is forbidden on the real-time audio thread — but in your setup/control code it's free.)
|
|
|
|
---
|
|
|
|
## Collections
|
|
|
|
### Arrays — ordered lists
|
|
|
|
```swift
|
|
let frequencies: [Double] = [440.0, 550.0, 660.0] // a major chord
|
|
print(frequencies[0]) // 440.0 (indexing starts at 0)
|
|
print(frequencies.count) // 3
|
|
```
|
|
|
|
### Dictionaries — key/value lookups
|
|
|
|
```swift
|
|
let noteToHz: [String: Double] = ["A4": 440.0, "C5": 523.25]
|
|
print(noteToHz["A4"]) // Optional(440.0) — note the "Optional"!
|
|
```
|
|
|
|
That `Optional` wrapper is important, and it's next.
|
|
|
|
---
|
|
|
|
## Optionals — Swift's "maybe there's a value"
|
|
|
|
A dictionary lookup might find nothing (`noteToHz["Z9"]`). Rather than crash or return a bogus value, Swift returns an **Optional**: a box that either holds a value or is `nil` (empty). An optional type is written with a trailing `?`:
|
|
|
|
```swift
|
|
let maybeHz: Double? = noteToHz["A4"] // Double? — might be nil
|
|
```
|
|
|
|
You **unwrap** an optional before using it. The safe, idiomatic way is `if let` / `guard let`:
|
|
|
|
```swift
|
|
if let hz: Double = noteToHz["A4"] {
|
|
print("Found \(hz)") // hz is a plain Double in here
|
|
} else {
|
|
print("No such note")
|
|
}
|
|
```
|
|
|
|
The annotation on an `if let` / `guard let` names the **unwrapped** type — `hz` is a plain `Double` inside the block, not a `Double?`.
|
|
|
|
Or supply a fallback with `??`:
|
|
|
|
```swift
|
|
let hz: Double = noteToHz["Z9"] ?? 440.0 // use 440 if the lookup was nil
|
|
```
|
|
|
|
> **The one rule you'll hear repeated:** avoid the force-unwrap operator `!` (as in `noteToHz["A4"]!`). It says "I promise this isn't nil" — and if you're wrong, the program crashes. Lyrebird's coding rules **forbid `!`** entirely, especially on the audio thread where a crash means a dropout or worse. Use `if let`, `guard let`, or `??`. Build the habit now.
|
|
|
|
`guard let` is the early-exit form, common at the top of functions:
|
|
|
|
```swift
|
|
func describe(_ note: String) {
|
|
guard let hz: Double = noteToHz[note] else {
|
|
print("Unknown note")
|
|
return // guard MUST leave the scope on failure
|
|
}
|
|
print("\(note) = \(hz) Hz") // hz is available for the rest of the function
|
|
}
|
|
```
|
|
|
|
---
|
|
|
|
## Control flow
|
|
|
|
```swift
|
|
// if / else
|
|
if gain > 1.0 {
|
|
print("clipping risk")
|
|
} else {
|
|
print("safe")
|
|
}
|
|
|
|
// for-in over a range (the loop variable takes an annotation too)
|
|
for i: Int in 0..<4 { // 0, 1, 2, 3 (..< excludes the end)
|
|
print(i)
|
|
}
|
|
for i: Int in 1...4 { // 1, 2, 3, 4 (... includes the end)
|
|
print(i)
|
|
}
|
|
|
|
// for-in over a collection
|
|
for freq: Double in frequencies {
|
|
print(freq)
|
|
}
|
|
|
|
// while
|
|
var x: Double = 1.0
|
|
while x < 8.0 { x *= 2.0 } // 1, 2, 4 → x ends at 8
|
|
|
|
// switch — must be exhaustive
|
|
let wave: String = "saw"
|
|
switch wave {
|
|
case "sine": print("smooth")
|
|
case "saw": print("bright")
|
|
default: print("something else")
|
|
}
|
|
```
|
|
|
|
Swift's `switch` is powerful and must cover every case (add `default` for the rest). No fall-through by accident.
|
|
|
|
---
|
|
|
|
## Functions
|
|
|
|
```swift
|
|
func midiToHz(_ note: Int) -> Double {
|
|
return 440.0 * pow(2.0, Double(note - 69) / 12.0)
|
|
}
|
|
|
|
let hz: Double = midiToHz(69) // 440.0 (MIDI 69 = A4)
|
|
```
|
|
|
|
- `func name(params) -> ReturnType { … }`.
|
|
- `_ note: Int` — the `_` means "no argument label at the call site," so you write `midiToHz(69)` not `midiToHz(note: 69)`. Without the `_`, the label is required.
|
|
- `-> Double` is the return type. A function returning nothing omits the arrow.
|
|
|
|
**Argument labels make calls read like prose** — you saw this with `OscSin.Audio(freq: 440.0, mul: 0.2)`. Use them; they're a Swift strength.
|
|
|
|
Default values reduce noise at call sites:
|
|
|
|
```swift
|
|
func tone(freq: Double, mul: Double = 0.2) -> OscSin.Audio {
|
|
return OscSin.Audio(freq: freq, mul: mul)
|
|
}
|
|
let a: OscSin.Audio = tone(freq: 440.0) // mul defaults to 0.2
|
|
let b: OscSin.Audio = tone(freq: 440.0, mul: 0.5) // override it
|
|
```
|
|
|
|
Lyrebird generators lean on defaults heavily — most take `mul:` and `add:` with sensible defaults so you only specify what matters.
|
|
|
|
---
|
|
|
|
## Error handling
|
|
|
|
Some functions can fail. They're marked `throws`, and you must call them with `try` inside a `do/catch`:
|
|
|
|
```swift
|
|
do {
|
|
try engine.start()
|
|
try engine.add(SineTone())
|
|
} catch {
|
|
print("Engine problem: \(error)")
|
|
}
|
|
```
|
|
|
|
You saw this in guide 1. The rule: **if the compiler demands `try`, the call can fail** — decide what to do in `catch`. In small programs, printing the error and exiting is fine:
|
|
|
|
```swift
|
|
do {
|
|
try engine.start()
|
|
} catch {
|
|
print("Failed to start: \(error)")
|
|
exit(1)
|
|
}
|
|
```
|
|
|
|
---
|
|
|
|
## Structs vs classes — and why Lyrebird uses classes
|
|
|
|
Swift has two ways to make your own types:
|
|
|
|
- **`struct`** — a **value type**. Copied when assigned or passed. Two variables never share the same struct.
|
|
- **`class`** — a **reference type**. Assigning passes a reference; two variables can point at the *same* object. Classes support inheritance (`: SomeBaseClass`).
|
|
|
|
```swift
|
|
struct Point { var x: Double; var y: Double }
|
|
var p1: Point = Point(x: 0.0, y: 0.0)
|
|
var p2: Point = p1 // a COPY
|
|
p2.x = 5.0 // p1.x is still 0
|
|
|
|
final class Counter { var n: Int = 0 }
|
|
let c1: Counter = Counter()
|
|
let c2: Counter = c1 // SAME object
|
|
c2.n = 5 // c1.n is now 5 too
|
|
```
|
|
|
|
Rule of thumb: **prefer `struct`** for plain data (a note, a frequency pair, a color). Use **`class`** when you need identity or inheritance.
|
|
|
|
**Synthesizers and generators are classes** — that's why guide 1 wrote `final class SineTone: SynthesizerBase`. A synthesizer *is a* `SynthesizerBase` (inheritance), and the engine tracks it by identity. You'll subclass `SynthesizerBase` for every sound you design and `override func build()` to describe its graph.
|
|
|
|
Mark classes you don't intend to subclass as `final` — it's clearer and lets the compiler optimize. Lyrebird's own synthesizer examples are all `final`.
|
|
|
|
---
|
|
|
|
## Best practices checklist
|
|
|
|
Carry these from day one — they're the difference between Swift that fights you and Swift that flows:
|
|
|
|
1. **`let` by default, `var` only when it changes.**
|
|
2. **Annotate the type on every `let` and `var`** (`let freq: Double = 440.0`). Clearer for readers, and faster to compile because Swift skips inference — a real win on large projects. The only exceptions are the few places Swift's grammar forbids it (closure params, tuple destructures, pattern bindings).
|
|
3. **Never force-unwrap with `!`.** Use `if let`, `guard let`, or `?? fallback`. (Non-negotiable in Lyrebird.)
|
|
4. **Let argument labels do their job** — they make call sites self-documenting.
|
|
5. **Prefer `struct` for data, `class` for identity/inheritance.** Mark classes `final` unless subclassing is intended.
|
|
6. **Convert number types explicitly** (`Double(n)`); don't fight the compiler, follow it.
|
|
7. **Handle errors where they happen** — `do/catch`, don't ignore `try`.
|
|
8. **Name things for what they mean** — `cutoffHz`, not `f`; `voiceCount`, not `n`.
|
|
9. **Small functions.** If `build()` gets long, extract helpers (guide 3 shows how).
|
|
|
|
The Lyrebird codebase enforces #2 as a hard rule, and adds one more on top: **no magic numbers** — name every non-trivial literal with a `let` (`let killQueueCapacity: Int = 32`). Both are documented in the project's `CLAUDE.md`. Annotation is a good habit in any Swift project; the magic-number rule matters most when you contribute to Lyrebird itself.
|
|
|
|
---
|
|
|
|
## What you learned
|
|
|
|
You can now read and write the Swift that Lyrebird programs are made of: values, types, optionals, control flow, functions, errors, and the struct/class distinction — plus the habits that keep it clean.
|
|
|
|
Next: [Types & Functional Programming](03-types-and-functional.md) — Swift's type system in depth and the functional tools (`map`, `filter`, closures) that make building synthesis graphs elegant.
|