In Swift, what is the difference between `open` and `public` on a class and its methods for code in another module?
answer
- use versus extend
- the module boundary is where it bites
- opt in per member too
- classes only
basics
~20 sBoth make a class and its members usable from other modules. Only open also lets another module subclass the class or override the member; a public class can be subclassed, and its public methods overridden, only inside its defining module.
solid answer
~50 sSwift splits two permissions that other access levels grant together: **using** a class and **extending** it. `public` lets any importing module use the class: name it, call its public initializers and methods, read its public properties. `open` adds subclassing outside the module for a class and overriding outside the module for a member, and it is set per declaration: an `open class` with a `public` method can be subclassed elsewhere but that method cannot be overridden there. The compiler reports `cannot inherit from non-open class` or `overriding non-open instance method outside of its defining module`. Inside the defining module there is no difference. `open` applies only to classes and overridable class members, and cannot be combined with `final`. Frameworks reach for `public` first because opening a class commits them to supporting subclasses they never see.
code
swift · 11 lines// Core module
open class HTTPClient {
public init() {}
open func send(_ path: String) -> String { "GET \(path)" } // overridable anywhere
public func resetCookies() {} // overridable only inside Core
}
public class RequestLogger { // subclassable only inside Core
public init() {}
public func log(_ line: String) { print(line) }
}go deeper
Recall that both levels make a class usable from other modules and that only open allows subclassing there.
Explain that open is checked per declaration, quote the two errors, and say why inside the module the distinction disappears.
Show why a framework defaults to public: override contracts, freedom to reorder internal calls, and the compiler's ability to treat unsubclassed classes as final.
Weigh an open class against a public class with a protocol customization point when designing a framework surface other teams build on.
## Two permissions, not one For most declarations, access control grants a bundle of rights at once: if you can see a type you can name it, create it, copy it and call its members. There are two exceptions: a property's setter can be restricted separately, and classes. For classes Swift separates **using** a class from **subclassing** it, and **calling** a member from **overriding** it. `public` grants the first of each pair to other modules; `open` grants both. | Question | `public` | `open` | |---|---|---| | Visible to and callable from another module | yes | yes | | Subclassable inside the defining module | yes | yes | | Subclassable from another module | no | yes | | Member overridable from another module | no | yes, when the member itself is `open` | | Applies to | any declaration | classes and overridable class members only | ## What the compiler reports Take a Core framework that exports `open class HTTPClient` with an `open` method `send(_:)` and a `public` method `resetCookies()`, plus `public class RequestLogger`. In a Feature module that imports Core: - subclassing `HTTPClient` and overriding `send(_:)` compiles; - overriding `resetCookies()` fails with `overriding non-open instance method outside of its defining module`; - subclassing `RequestLogger` fails with `cannot inherit from non-open class 'RequestLogger' outside of its defining module`. Misusing the keyword is caught too: `open struct` gives `only classes and overridable class members can be declared 'open'; use 'public'`, and `open final class` gives `class cannot be declared both 'final' and 'open'`. The key detail is that **`open` is per declaration**. An open class does not open its members; each method, property or subscript that outside subclasses may override has to say `open` itself. ## Inside the module nothing changes Within Core, any accessible class can be subclassed and any visible member overridden, whether it is `public` or `open`; the tool for forbidding that inside the module is `final`, which belongs with the material on subclassing and overrides. That is why the difference often surfaces late: Core's own tests and helpers subclass freely, and the error appears the first time another module tries. ## Why frameworks default to `public`, not `open` 1. **Subclassing is a contract.** An overridable method promises when it is called, whether an override must call `super`, and which invariants hold at that point. Marking a class `open` says the author designed for code they cannot see. 2. **Freedom to change.** With `public`, Core can reorder internal calls between its methods without breaking an outside subclass that relied on that order. 3. **Optimization.** The proposal that added `package` notes that the compiler applies its normal optimization model to `public` classes and methods, treating them as `final` when nothing in the module subclasses or overrides them; the dispatch details belong with the material on method call mechanisms. ## Related rules worth knowing - `package` behaves like `public` here: a `package class` cannot be subclassed from another module, even one in the same package, and Swift has no spelling for "open within the package". - `@testable import` imports `internal` and `public` classes and members **as if** they were `open`, so test doubles can subclass a public class; production modules cannot. - A subclass cannot be more visible than its superclass: a `public` subclass of an `internal` class is rejected. An override, though, may be more visible than the method it overrides. ## Where the decision shows up in a modular app In an app split into a Core framework and Feature modules, the question comes up as soon as Feature wants a variant of something Core provides. Three answers exist, and only one of them requires `open`: 1. **Subclass**: Core marks the class and the specific hooks `open`, and documents the override contract. 2. **Compose**: Feature wraps a `public` Core type and forwards to it, adding behaviour around the calls. 3. **Inject**: Core accepts a value conforming to a `public` protocol and calls it at the customization point. When reviewing a framework, ask of every `open`: is there a real outside subclass, and is the override contract documented? Where the answer is no, a `public` class plus a protocol for the customization point is usually the better surface.
- Core has `open class HTTPClient` with a `public func resetCookies()`. Can an app subclass override `resetCookies()`?No. Opening the class allows subclassing outside Core, but each member is checked separately: `resetCookies()` is only `public`, so the override fails with `overriding non-open instance method outside of its defining module`. The subclass can still call it, and can override any member Core marked `open`.
- Why might a framework keep a class `public` and expose a protocol instead of making the class `open`?A protocol names exactly the customization points and their contract, leaves the class's internal call order free to change, and lets structs and actors conform too. An open class exposes every open member as an override point whose timing and `super` requirements become part of the API, and the framework must keep those stable for subclasses it never sees.
- public classes can be subclassed from any module that imports them
- Marking a class open makes all of its methods overridable everywhere
- open can be used on structs and enums to allow extension
- Inside its own module a public class cannot be subclassed
- package classes can be subclassed by other modules in the same package