Skip to content
Learn Netverks

Lesson

Step 23/36 64% through track

generics-swift

Generics

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

This lesson

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

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

You will apply Generics 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.

Generics write flexible, type-safe functions and types—like templates in C++ or generics in Kotlin and C#, with constraints via protocol requirements.

Generic functions and types

func swapValues<T>(_ a: inout T, _ b: inout T) {
    let temp = a; a = b; b = temp
}

struct Stack<Element> {
    private var items: [Element] = []
    mutating func push(_ item: Element) { items.append(item) }
    mutating func pop() -> Element? { items.popLast() }
}

Constraints

func max<T: Comparable>(_ a: T, _ b: T) -> T { a > b ? a : b }

Important interview questions and answers

  1. Q: where clauses?
    A: Refine associated types on protocols—func process<C: Collection>(_ c: C) where C.Element == Int.
  2. Q: Generics vs Any?
    A: Generics preserve type information and enable optimization; Any erases types and requires runtime casting.

Self-check

  1. How do you constrain a generic to Comparable?
  2. Can structs be generic?

Tip: Prefer generics over Any—preserves type safety and enables optimizer specialization.

Interview prep

where clauses?

Refine generic constraints on associated types and relationships.

Generics vs Any?

Generics preserve types; Any erases and requires casting.

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

  • some vs any?
  • where constraints?

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