skip to content

Requirements and Conformance

A protocol lists requirements that conforming types satisfy, often in an extension, and protocols compose with &. Interviewers ask how protocol-oriented design replaces class hierarchies.

on this pageshow

explore

questions

6

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

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

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

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