In Swift, what is the difference between declaring a type method with `static` and with `class`, and where can each be used?
answer
- both belong to the type
- only one is overridable
- classes only for one of them
- static in a class is final
basics
~20 sBoth declare type methods, called on the type rather than an instance. Structs and enums can only use static; classes can use either, and a class method may be overridden by a subclass while a static one, equivalent to class final, cannot.
solid answer
~40 sA type method belongs to the type itself: you call `Renderer.makeDefault()`, and inside it `self` refers to the type, not an instance. Structures and enumerations declare type methods only with `static`; writing `class func` in a struct fails with "class methods are only allowed within classes; use 'static' to declare a static method". Inside a class you choose: `class func` lets a subclass provide its own implementation with `override class func`, while `static func` has the same effect as `class final` and cannot be overridden — the compiler says "cannot override static method". When you call through a metatype such as `let kind: Renderer.Type = MetalRenderer.self`, `kind.backendName()` runs the subclass's version. Type methods cannot be called on an instance: `p.t()` is rejected, so instance code calls them as `Self.t()` or through the type name.
code
swift · 19 linesclass Renderer {
static func apiVersion() -> Int { 3 } // fixed: same as class final
class func backendName() -> String { "base" } // a subclass may override
class func makeDefault() -> Renderer { Renderer() }
func describe() -> String {
"\(Self.backendName()) v\(Self.apiVersion())"
}
}
final class MetalRenderer: Renderer {
override class func backendName() -> String { "metal" }
override class func makeDefault() -> Renderer { MetalRenderer() }
}
let kind: Renderer.Type = MetalRenderer.self
print(kind.backendName()) // metal
print(MetalRenderer().describe()) // metal v3
print(kind.makeDefault() is MetalRenderer) // truego deeper
Recall that static and class both declare type methods called on the type, and that structs and enums can only use static.
Explain that class allows an override in a subclass while static in a class equals class final, and that self inside a type method is the type.
Show how a class type method behaves when called through a metatype or Self, and use static by default so only deliberately variable methods are overridable.
Treat class type methods as part of a hierarchy's extension surface: each one is a promise to subclassers that is hard to withdraw later.
## Type methods versus instance methods An **instance method** runs on a particular value or object. A **type method** belongs to the type itself and is called on the type: `Theme.reload()`, `Renderer.makeDefault()`. Swift lets classes, structures and enumerations all declare type methods. Typical uses are factory methods, helpers that work on shared type-level state, and parsing entry points that produce a new instance. Inside a type method, the implicit `self` refers to **the type**, not an instance. Unqualified names in the body resolve to other type-level members, so a type method can call another type method or read a type property without the type-name prefix. It cannot touch instance members: calling an instance method from a static method fails with `instance member 'inst' cannot be used on type 'P'`. The reverse is also checked — `p.t()` on an instance reports `static member 't' cannot be used on instance of type 'P'` — so instance code calls a type method as `Self.t()` or `P.t()`. ## The two keywords Swift has two keywords for a type method, and the difference comes down to subclassing: - **`static`** works in structures, enumerations and classes. In a class it means the method cannot be overridden; the Swift reference says `static` there has the same effect as marking the declaration `class` and `final`. - **`class`** is allowed **only inside classes**, and it lets a subclass replace the implementation with `override class func`. | Declaration | Where it is allowed | Can a subclass override it? | |---|---|---| | `static func` in a struct or enum | structs, enums | not applicable: no subclasses | | `static func` in a class | classes | no: `cannot override static method` | | `class func` | classes only | yes, with `override class func` | | `final class func` | classes only | no: `class method overrides a 'final' class method` | Writing `class func` inside a struct is a compile error whose message also names the fix: `class methods are only allowed within classes; use 'static' to declare a static method`. The same two keywords apply to type subscripts, and a `static subscript` in a class is likewise equivalent to `class final`. ## What overriding a type method buys you Because a `class` type method can be overridden, the implementation that runs depends on **which type you call it on**. That matters when code works with a metatype value rather than a type name: 1. `let kind: Renderer.Type = MetalRenderer.self` stores a subclass's type in a variable of the base metatype. 2. `kind.backendName()` runs `MetalRenderer`'s override, not the base implementation. 3. Inside an instance method, `Self.backendName()` uses the dynamic type of the instance, so a `MetalRenderer` object describes itself as `metal`. This is the reason to reach for `class`: a family of related classes where each subclass customises a factory or a type-level description. If nothing should vary per subclass, `static` documents that and keeps the method out of the override surface. ## Choosing between them - In a **struct or enum**, there is no choice: use `static`. - In a **class whose type methods are utilities**, use `static`. It states that the behaviour is fixed for every subclass. - In a **class designed for subclassing**, use `class` for exactly the type methods a subclass is expected to replace, such as a factory that must build the subclass. - If the class is already `final`, the two keywords behave the same, and `static` is the conventional spelling. How an overridden type method is chosen at run time, and what `final` does to the cost of a call, are covered with method dispatch; the rules for `override` itself — the keyword being required and checked — are covered with subclassing. What belongs to this lesson is the declaration choice: which keyword the type allows, and whether you are opening the method to subclasses. ## Type methods and stored type state Type methods often work with **type properties** such as a shared registry or a configuration cache. A static method can read and write a `static var` directly by name. Keep in mind that such state is global: every caller in the process sees the same value. That is the point of a shared configuration, and it is also why Swift 6 language mode rejects a plain mutable `static var` as `not concurrency-safe because it is nonisolated global shared mutable state` unless it is isolated or otherwise protected.
- Inside a Swift class's instance method, what is the difference between calling `Renderer.backendName()` and `Self.backendName()`?`Renderer.backendName()` names the base class explicitly, so it always runs the base implementation. `Self` refers to the dynamic type of the current instance, so on a `MetalRenderer` object `Self.backendName()` runs the subclass's override. Use `Self` when the type method is meant to vary with the subclass.
- Why might a team prefer `static` over `class` for type methods even in a class hierarchy?`static` closes the method to overriding, so subclasses cannot change behaviour the base class relies on, and readers know the implementation is fixed. Making it `class` adds the method to the surface subclasses may override; do that only for methods designed to vary, such as a factory that should build the subclass.
- Says class func is allowed in structs as a synonym for static
- Believes static methods in a class can be overridden
- Claims a type method can read instance properties through self
- Says static methods can be called on an instance like instance methods
- Thinks class and static differ in storage or lifetime, not overriding