What can a Swift extension add to an existing type, what can it not add, and why declare a protocol conformance in one?
answer
- new behaviour, never new instance storage
- computed yes, stored no
- classes: convenience inits only
- one extension per conformance
basics
~20 sAn 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 sAn 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 linesstruct 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
Recall the list: computed properties, methods, initializers, subscripts, nested types and conformances yes; stored instance properties, observers, deinit and class designated initializers no.
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.
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.
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.