skip to content

Protocol-Oriented Design

Protocols define requirements, extensions add behaviour, and together they let Swift compose rather than subclass. Interviewers test protocol-oriented design and its dispatch traps.

on this pageshow

explore

questions

16

What can a Swift extension add to an existing type, what can it not add, and why declare a protocol conformance in one?

level: juniorimportance: must knowfreq 68%

answer

  1. new behaviour, never new instance storage
  2. computed yes, stored no
  3. classes: convenience inits only
  4. one extension per conformance

basics

~20 s

An extension adds computed properties, methods, initializers, subscripts, nested types and protocol conformances. It cannot add stored instance properties, property observers, deinitializers or, on a class, designated initializers. Declaring a conformance in an extension groups that protocol's members.

solid answer

~40 s

An extension adds functionality to a class, struct, enum or protocol, even one from another module: computed instance and type properties, instance and type methods, initializers, subscripts, nested types and new protocol conformances. It cannot change a type's memory layout, so stored instance properties and property observers are rejected ("extensions must not contain stored properties"); static stored properties are fine because they live outside instances. On a class, an extension may add convenience initializers but not designated ones or a `deinit`, and it cannot override existing members. Writing `extension CacheKey: CustomStringConvertible { ... }` keeps each conformance's members together, and an empty `extension Hamster: TextRepresentable {}` adopts a protocol whose requirements the type already meets, because conformance is never inferred from shape alone.

code

swift · 23 lines
swift
struct CacheKey {
    var namespace: String
    var id: Int
}

extension CacheKey {
    static let separator: Character = ":"   // type stored property: allowed
    var rawValue: String { "\(namespace)\(Self.separator)\(id)" }

    init?(rawValue: String) {
        let parts = rawValue.split(separator: Self.separator)
        guard parts.count == 2, let id = Int(parts[1]) else { return nil }
        self.init(namespace: String(parts[0]), id: id)   // memberwise init still exists
    }
}

extension CacheKey: CustomStringConvertible {
    var description: String { "CacheKey(\(rawValue))" }
}

let key = CacheKey(namespace: "thumbs", id: 42)
print(key.rawValue)
print(CacheKey(rawValue: "thumbs:7") ?? key)

go deeper

for a junior

Recall the list: computed properties, methods, initializers, subscripts, nested types and conformances yes; stored instance properties, observers, deinit and class designated initializers no.

for a middle

Explain the layout reason behind the no-storage rule, why static stored properties are allowed, and how a struct keeps its memberwise initializer when you add one in an extension.

for a senior

Use extensions deliberately: one per conformance for review, the empty-extension adoption idiom, and composition or wrapper types when someone asks for per-instance state on a type you do not own.

for a principal

Set conventions for where conformances live, in the type's file or beside the protocol, so reviewers can find them, and keep extensions on other modules' types small and owned by one place.

## What an extension is An **extension** adds new functionality to an existing class, structure, enumeration or protocol, including types whose source you do not own. The Swift book lists what it can add: - computed instance properties and computed type properties; - instance methods and type methods (with `mutating` methods on value types); - new initializers; - subscripts; - new nested types; - conformance to a protocol. Extensions have no names, and an extension can add functionality but cannot override what the type already has. ## What an extension cannot add | Attempt | Result in the Swift 6.4 compiler | |---|---| | `var hits: Int = 0` (stored instance property) | error: extensions must not contain stored properties | | `didSet` on a new or existing stored property | rejected; stored properties and property observers belong in the type's body | | designated `init` on a class | error: designated initializer cannot be declared in an extension of 'DiskCache'; did you mean this to be a convenience initializer? | | `deinit` | error: deinitializers may only be declared within a class, actor, or noncopyable type | | `static let separator = ":"` | accepted: a type stored property is not part of each instance | The reason is layout. A type's **stored instance properties** decide how big each instance is and how it is initialized; the type's own declaration fixes that, and an extension (possibly in another module) cannot change it. A static stored property is a lazily initialized global namespaced by the type, so it does not touch instance layout. The book's reference chapter says flatly that extensions can't contain stored properties; the compiler accepts static ones, and the compiler's verdict is the one your build sees. ## Initializers in extensions 1. **Structs keep their memberwise initializer.** Adding `init?(rawValue:)` in an extension of a struct that defines no initializer in its body leaves the memberwise initializer available, and the new initializer can delegate to it. Writing the same initializer inside the struct body would suppress the memberwise one. 2. **Classes take only convenience initializers.** A designated initializer must set every stored property, and only the class's own declaration owns them. An extension's convenience initializer must delegate to `self.init(...)`. 3. **Types from another module.** An initializer added to another module's struct must call one of that module's initializers before using `self`. ## Declaring conformance in an extension Two idioms are everyday Swift: - **One extension per conformance.** `extension CacheKey: CustomStringConvertible { var description: String { ... } }` keeps the protocol's members together and makes the conformance easy to find and review. - **Adopting a protocol the type already satisfies.** Swift never infers conformance from a type's shape: a struct with a matching `textualDescription` does not conform to `TextRepresentable` until something says so. An empty `extension Hamster: TextRepresentable {}` is enough. (A few marker protocols, such as `Copyable`, are inferred by the compiler; ordinary protocols never are.) Existing instances of a type gain a conformance as soon as the extension declaring it is compiled in. Extending a type you do not own to conform to a protocol you do not own raises a further question about retroactive conformance, which belongs with protocol extensions and default implementations. ## What to say in an interview Lead with the rule of thumb, *new behaviour, no new instance storage*, then give the two exceptions people forget: static stored properties are allowed, and a struct's memberwise initializer survives an extension initializer. Close with why teams declare conformances in extensions: grouping, readability, and the empty-extension adoption idiom.

  • How do you attach per-instance state to a type you cannot modify, given that extensions cannot store it?
    Wrap or compose instead: store the type inside your own struct or class that adds the property, or keep a side table such as a dictionary keyed by an identifier. A computed property in an extension can read from that storage, but the storage itself must live in a type whose declaration you own.
  • Why can a Swift extension add a convenience initializer to a class but not a designated one?
    A designated initializer must initialize every stored property the class declares and call a superclass designated initializer; only the class body owns that layout and chain. A convenience initializer just delegates to an existing initializer with `self.init(...)`, so it needs no knowledge of storage. The compiler suggests converting the designated initializer to a convenience one.

  • Extensions can add stored properties as long as they have a default value.
  • Adding an initializer in a struct extension removes the memberwise initializer.
  • A type that has all the right members conforms to a protocol automatically.
  • An extension can override a method the type already declares.
  • Static stored properties are forbidden in extensions just like instance ones.
open as a page

In a Swift protocol, what separates a `{ get }` property requirement from a `{ get set }` one, and which conformer properties satisfy each?

level: juniorimportance: must knowfreq 62%

basics

~20 s

A { get } requirement accepts any property of that name and type: a let, a var or a read-only computed property. A { get set } requirement needs something settable: a stored var or a computed property with a setter.

open as a page

In Swift, how does a type conforming to a protocol with an `associatedtype` choose the concrete type, and when must it write a typealias?

level: middleimportance: must knowfreq 60%

basics

~20 s

An associatedtype is a placeholder each conformer fills. Swift usually infers it from the witnesses, such as save(_ entity: User); write typealias Entity = User when no requirement mentions it, when inference is ambiguous, or to make the choice explicit.

open as a page

In Swift, how does a protocol extension supply a default implementation for a requirement, and when does a conforming type's own version replace it?

level: middleimportance: must knowfreq 75%

basics

~20 s

A protocol extension can implement a method or computed-property requirement, and conformers that declare nothing get it. A conformer declaring a member with the same name, argument labels and types replaces that default everywhere, including calls through the protocol.

open as a page

Why does Swift reject `weak var delegate: CacheDelegate?` until the `CacheDelegate` protocol inherits from `AnyObject`?

level: middleimportance: must knowfreq 72%

basics

~20 s

A weak reference only makes sense for class instances, and a plain protocol can be adopted by structs and enums. Adding AnyObject to the protocol's inheritance list makes it class-only, so the compiler knows every conformer is a reference and accepts weak.

open as a page

Before Swift 5.7, why could a protocol with an `associatedtype` or `Self` requirement be used only as a generic constraint, and what is still restricted today?

level: seniorimportance: must knowfreq 55%

basics

~20 s

A protocol-typed value hides its concrete type, so Swift cannot know what Entity or Self means there. Before 5.7 such protocols were rejected as types; now any Repository compiles, but members taking Entity or Self as parameters stay unusable.

open as a page

A Swift Logger protocol's extension adds a format(_:) helper the protocol never declares; why is a conformer's own format(_:) ignored when called through the protocol?

level: seniorimportance: must knowfreq 70%

basics

~20 s

Only protocol requirements reach a conformer's own implementation through the protocol. An extension-only member like format(_:) is chosen at compile time from the static type, so through any Logger, a generic parameter or self in the extension, the extension's version runs.

open as a page

In a Swift protocol, what does capital `Self` mean in a requirement such as `func copy() -> Self`?

level: juniorimportance: should knowfreq 45%

basics

~20 s

In a protocol, Self stands for the eventual conforming type: func copy() -> Self obliges a struct Draft to return a Draft, not just any conforming value. Lowercase self is the instance; a non-final class must write the return type as Self.

open as a page

In a Swift protocol, how do you constrain an `associatedtype` with a protocol or a `where` clause, and what does that constraint buy?

level: middleimportance: should knowfreq 35%

basics

~20 s

Write a conformance after the name (associatedtype Entity: Identifiable) or a where clause relating it to another (where Batch.Element == Entity). Every conformer's choice is checked against it, and code written against the protocol may then use those guarantees.

open as a page

In Swift, when do you write a protocol composition like `Codable & Sendable` instead of declaring a new protocol that inherits both?

level: middleimportance: should knowfreq 42%

basics

~20 s

Use a composition such as Codable & Sendable when a value just needs several protocols at once: any type conforming to all of them qualifies. Declare an inheriting protocol for a named concept with its own requirements or extensions; conformers must adopt it explicitly.

open as a page

In Swift, why does a protocol mark a method requirement `mutating`, and how do struct and class conformers satisfy it?

level: middleimportance: should knowfreq 45%

basics

~20 s

Marking a requirement mutating lets structs and enums satisfy it with a method that changes self. Classes implement it without the keyword. A non-mutating implementation also satisfies it, but a mutating one cannot satisfy a non-mutating requirement.

open as a page

What does declaring a primary associated type, as in Swift's `protocol Repository<Entity>`, let callers write that a plain `associatedtype` does not?

level: seniorimportance: should knowfreq 30%

basics

~20 s

It lets the protocol take type arguments: Repository<User> means conforms to Repository with Entity == User. The shorthand works in generic constraints and extensions, and it is the only way to constrain Entity on some or any types.

open as a page

In Swift, how does a conditional conformance such as extension Array: Equatable where Element: Equatable work, and what are its limits?

level: seniorimportance: should knowfreq 50%

basics

~20 s

A generic type conforms to a protocol only when its type arguments meet the where clause, so [Int] is Equatable and [Any] is not. A type gets one conformance per protocol, and inherited protocols must be stated separately.

open as a page

Why does the Swift 6 compiler warn about extension Date: Identifiable in an app, and what does marking it @retroactive change?

level: seniorimportance: should knowfreq 40%

basics

~20 s

Date and Identifiable both come from other modules, so this is a retroactive conformance: if Foundation later declares the same one, which implementation wins is not under your control. Writing @retroactive just acknowledges the risk and silences the warning.

open as a page

A Swift protocol requires `init(snapshot:)`; why does an extension adding that initializer to a non-final class fail to compile, and how do you fix it?

level: seniorimportance: should knowfreq 30%

basics

~20 s

Subclasses inherit a class's protocol conformance, so every subclass must also provide the initializer; Swift enforces that with a required initializer, which must be declared in the class body. Move a required init into the class, or mark the class final.

open as a page

As the lead of a multi-module Swift app, what rules would you set for retroactive conformances and public protocol extensions across modules?

level: principalimportance: should knowfreq 30%

basics

~20 s

Give each conformance one owner: the type's module or the protocol's. Keep unavoidable retroactive conformances in the app target, marked and justified, prefer wrapper types, and choose deliberately which protocol members are requirements and who may extend shared protocols.

open as a page