Reference

How types work

Swift reads your code before it runs it, and it refuses to run code that can’t make sense — a number that might be nil, a whole number added to a decimal, a switch that forgets a case. That’s the compiler catching bugs early. Here are the ideas the lab drills. Open the compile lab →

  • A type error is the compiler on your side

    The red error isn’t the compiler being difficult — it caught a bug BEFORE the code ran. Every error you fix at compile time is a crash a user never sees.

  • An optional might be nil — so you must handle it

    An `Int?` is a number OR nil. Swift won’t let you use it as if it’s always there. Unwrap it with `if let`, force it with `!` (only when you’re sure), or give a default with `??`.

  • Swift won’t silently mix a whole number and a decimal

    `3` is an `Int`; `0.5` is a `Double`. `3 + 0.5` won’t compile — Swift never converts for you. Make both sides the same kind: `3.0 + 0.5`.

  • A let never changes; a var can

    `let` means "this value is fixed". Reassigning it is a compile error. If something must change, use `var`.

  • A switch must cover every case

    A `switch` over an enum must handle every case (or add a `default`). The compiler makes sure you never forget one — including the case you add to the enum next year.

  • Read the fix, not just the change

    Many changes make code compile. Only some keep it doing what it was meant to do — a catch-all `default` compiles, but it can quietly give the wrong answer. The right fix does both.

Compile errors you’ll meet — and the fix

  • must be unwrapped

    You used an optional (`Int?`) directly. Unwrap it first: `if let`, `!`, or `??`.

  • can't mix Int and Double

    One side is a whole number, the other a decimal. Make them match.

  • 'let' constant can't change

    You reassigned a `let`. Use `var` if it needs to change.

  • switch must be exhaustive

    A case is missing. Add it (or a `default:` for the ones you don’t list).

  • cannot find in scope

    A name was used before it was made — a typo, or a `let`/`var` you forgot.

The programs are original teaching examples in a teaching subset of the Swift language — enough to meet the type system that catches these bugs. Nothing you read leaves your device. Read a program →