skip to content

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%

answer

  1. subclasses inherit the conformance
  2. the required modifier
  3. declared in the class body, not an extension
  4. final removes the obligation

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.

solid answer

~40 s

An initializer requirement is reached through the type, for example `type.init(snapshot:)` on a `C.Type` in generic code, and that metatype may be a subclass. Since subclasses inherit the conformance, Swift demands that a non-final class satisfy the requirement with a `required` initializer, which every subclass must then provide or inherit. A `required` initializer cannot be declared in an extension, so `extension DiskCache: CacheRestorable { convenience init(snapshot:) }` fails with "initializer requirement 'init(snapshot:)' can only be satisfied by a 'required' initializer in the definition of non-final class 'DiskCache'". Fixes: declare `required init(snapshot:)` (designated or convenience) in the class body, or mark the class `final`, after which a plain initializer in an extension is accepted. Structs and enums have no such rule.

code

swift · 25 lines
swift
protocol CacheRestorable {
    init(snapshot: [String: String])
}
final class DiskCache {
    var storage: [String: String]
    init() { storage = [:] }
}
extension DiskCache: CacheRestorable {
    convenience init(snapshot: [String: String]) {
        self.init()
        storage = snapshot
    }
}
class MemoryCache: CacheRestorable {
    var storage: [String: String]
    required init(snapshot: [String: String]) { storage = snapshot }
}
class ExpiringCache: MemoryCache {
    var ttl: Double = 60
}
func restore<C: CacheRestorable>(_ type: C.Type, from snapshot: [String: String]) -> C {
    type.init(snapshot: snapshot)
}
let e = restore(ExpiringCache.self, from: ["k": "v"])
print(type(of: e), e.storage)

go deeper

for a junior

Recall that a class satisfying a protocol initializer requirement marks it required unless the class is final.

for a middle

Explain why: subclasses inherit the conformance, and generic code calls the initializer through a metatype that may be a subclass.

for a senior

Diagnose the extension case from the two compiler messages, choose between a required initializer in the body and a final class, and predict which subclasses inherit the initializer and which must write it.

for a principal

Weigh the extensibility cost: a required initializer binds every future subclass, so prefer final classes or value types for protocol-constructed models unless subclassing is a real requirement.

## Initializer requirements and who must honour them A protocol can require an initializer: `protocol CacheRestorable { init(snapshot: [String: String]) }`. Generic code uses it through the **metatype**: ```swift func restore<C: CacheRestorable>(_ type: C.Type, from snapshot: [String: String]) -> C { type.init(snapshot: snapshot) } ``` For a struct or enum, `C.Type` names exactly one type. For a class it does not: **subclasses inherit their superclass's protocol conformances**, so `restore(ExpiringCache.self, ...)` is legal whenever `ExpiringCache` subclasses a conforming `MemoryCache`. The call must construct an `ExpiringCache`, which only works if that subclass also has `init(snapshot:)`. Swift guarantees this with the **`required` modifier**. When a non-final class satisfies a protocol initializer requirement, the implementation must be marked `required`, whether it is a designated or a convenience initializer. Every subclass must then provide that initializer, explicitly or by automatic inheritance. ## The three errors you meet | Code | Swift 6.4 compiler output | |---|---| | `init(snapshot:)` without `required` in a non-final class body | initializer requirement 'init(snapshot:)' can only be satisfied by a 'required' initializer in non-final class 'Plain' | | `convenience init(snapshot:)` in an extension of a non-final class | ... can only be satisfied by a 'required' initializer in the definition of non-final class 'DiskCache' | | `required convenience init(snapshot:)` in an extension | 'required' initializer must be declared directly in class 'MemCache' (not in an extension) | The last two together explain the extension case: the requirement demands `required`, and `required` is only legal in the class's own declaration, so no extension of a non-final class can satisfy an initializer requirement. ## Fixes 1. **Declare it in the class body.** `required init(snapshot: [String: String]) { storage = snapshot }` inside `class MemoryCache: CacheRestorable`. The conformance itself can still be written in an extension; only the initializer must live in the body. 2. **Mark the class `final`.** A final class has no subclasses, so the compiler accepts a plain designated or convenience initializer, including one in an extension: `final class DiskCache` plus `extension DiskCache: CacheRestorable { convenience init(snapshot:) { self.init(); storage = snapshot } }` compiles. 3. **For a class that subclasses another and satisfies the requirement with an initializer that also overrides**, write both modifiers: `required override init()`. ## Consequences for subclasses Once `MemoryCache` has a `required init(snapshot:)`: - A subclass that adds no designated initializers and gives its new stored properties default values, such as `ExpiringCache` with `var ttl: Double = 60`, **inherits** the required initializer automatically, and `restore(ExpiringCache.self, from: ["k": "v"])` returns an `ExpiringCache`. - A subclass that defines its own designated `init(label:)` stops inheriting initializers and must write the required one itself, or the compiler reports "'required' initializer 'init(snapshot:)' must be provided by subclass of 'MemoryCache'". - An override of it is written `required init(snapshot:)`; writing `override init(snapshot:)` instead is rejected with "use the 'required' modifier to override a required initializer". ## Reading the diagnostics quickly - "in the definition of non-final class" means the initializer lives in an extension; move it into the class body or make the class `final`. - "in non-final class" without that phrase means the initializer is in the body but lacks `required`. - "must be provided by subclass" means a subclass stopped inheriting initializers by defining its own designated one. ## Interview framing This is a diagnosis question with one right answer: the conformance is inherited, the metatype may be a subclass, so the initializer must be `required`, and `required` cannot live in an extension. Strong candidates name both fixes and mention the cost of the first, that every future subclass with its own designated initializer must implement the requirement too.

  • A subclass of `MemoryCache` adds `init(label:)` and gets "'required' initializer 'init(snapshot:)' must be provided by subclass". Why did inheritance stop?
    Defining its own designated initializer turns off automatic initializer inheritance, so the subclass no longer inherits `init(snapshot:)`. Because that initializer is `required`, the subclass must write `required init(snapshot:)` itself, initializing its new stored property and delegating to `super.init(snapshot:)`.
  • Does a struct conforming to `CacheRestorable` need `required` on its `init(snapshot:)`?
    No. `required` exists only for class inheritance; a struct or enum cannot be subclassed, so any initializer with the right signature satisfies the requirement, and it may be declared in an extension like any other initializer.

  • Adding required to the convenience init in the extension fixes it.
  • The required modifier is only for initializers inherited from Objective-C classes.
  • Subclasses do not inherit their superclass's protocol conformances.
  • Making the class final has no effect on initializer requirements.
  • A subclass overrides a required initializer with override, not required.