Skip to content
Learn Netverks

Lesson

Step 21/36 58% through track

protocols-swift

Protocols

Last reviewed May 28, 2026 Content v20260528
Track mode
server_compiled
Means
Compiled runner
Reading
~1 min
Level
intermediate

This lesson

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

Protocol-oriented design is Swift’s answer to composition—preferred over deep inheritance hierarchies.

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

Protocols define requirements that types adopt—Swift’s primary abstraction for polymorphism, comparable to interfaces in Java, Kotlin, and C#, but with extension default implementations.

Defining and conforming

protocol Describable {
    var label: String { get }
    func describe() -> String
}

struct User: Describable {
    let label: String
    func describe() -> String { "User: \(label)" }
}

Protocol-oriented programming

Extend protocols with default implementations; compose small protocols instead of deep class hierarchies—core Swift design philosophy.

Important interview questions and answers

  1. Q: Protocol vs abstract class?
    A: Protocols work with structs, enums, and classes; support retroactive modeling via extensions; no stored state in the protocol itself.
  2. Q: Any vs protocol type?
    A: Existential any Protocol (Swift 5.7+) boxes heterogeneous conformers; generics preserve concrete types at compile time.

Self-check

  1. Can structs conform to protocols?
  2. What keyword marks protocol adoption?

Tip: Compose small protocols—Swift favors protocol-oriented design over deep inheritance.

Interview prep

Protocol vs abstract class?

Protocols work with structs/enums; no stored state; extensions add defaults.

any Protocol?

Existential boxes heterogeneous conformers; generics preserve concrete types.

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

  • Protocol extension?
  • Existential any?

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