Skip to content
Learn Netverks

Lesson

Step 17/36 47% through track

pattern-matching-swift

Pattern matching

Last reviewed Jun 1, 2026 Content v20260601
Track mode
server_compiled
Means
Compiled runner
Reading
~1 min
Level
intermediate

This lesson

This lesson teaches Pattern matching: the syntax, patterns, and safety habits you need before advancing in Swift.

Teams still ship Pattern matching in Swift codebases—skipping it leaves gaps in debugging and code reviews.

You will apply Pattern matching in contexts like: iPhone/iPad/Mac apps, server-side Swift (niche), and Apple toolchain projects.

Write Swift in main.swift with print(), click Run on server—the dev runner swiftc compiles and runs the binary (requires Swift toolchain, typically macOS; LEARNING_RUNNER_ENABLED=true).

When you can explain the previous lesson's ideas without copying starter code.

Swift’s switch, if case, and guard case support rich pattern matching—especially powerful with enums and tuples.

switch on enums

switch state {
case .idle:
    print("waiting")
case .loaded(let count):
    print("\(count) items")
case .failed(let message):
    print(message)
}

Exhaustive switching—compiler errors if you miss a case when enums are closed.

where clauses and ranges

switch value {
case let x where x < 0: print("negative")
case 0: print("zero")
default: print("positive")
}

Important interview questions and answers

  1. Q: Exhaustive switch benefit?
    A: Compiler forces handling new enum cases—safer refactors than stringly-typed state.
  2. Q: if case vs switch?
    A: if case matches one pattern inline—useful for single-case checks without full switch boilerplate.

Self-check

  1. Why must enum switches be exhaustive?
  2. How do you bind associated values in a case?

Tip: Exhaustive switch on enums catches new cases at compile time after refactors.

Interview prep

Exhaustive switch?

Compiler requires all enum cases—safer refactors.

if case?

Matches one pattern inline without full switch.

Interview tip Lesson completion confidence

Can you explain this lesson in 30 seconds without reading notes?

Not saved yet.

Playground

Runs on the configured server runner (dev: npm run runner with LEARNING_RUNNER_ENABLED=true). Output appears below the editor.

Check yourself

Multiple choice — immediate feedback.

Discussion

Past discussion is visible to everyone. Only logged-in users can post comments and replies.

Starter discussion topics

  • switch on enum?
  • where clause?

Sign up or log in to post comments and sync lesson progress across devices.

No discussion yet. Be the first to ask a question.

Jump