Skip to main content
A class method in Swift is a type-level method associated with a class itself rather than an instance of that class. Declared using the class keyword, these methods are invoked directly on the class type and, crucially, utilize dynamic dispatch, allowing them to be overridden by subclasses.

Syntax and Invocation

A class method is defined by prefixing the func keyword with the class modifier. It is invoked using dot syntax on the type name.

Overriding Class Methods

Because class methods are dynamically dispatched, a subclass can provide its own implementation of a superclass’s class method using the override keyword.

class vs. static

Both class and static define type methods, but they differ in their dispatch mechanisms and inheritance rules:
  • class func: Dynamically dispatched. Can be overridden by subclasses.
  • static func: Statically dispatched. Cannot be overridden. In the context of a class, declaring a method as static func is functionally identical to declaring it as final class func.

The self Keyword in Class Methods

Within the body of a class method, the implicit self property refers to the class type itself, not an instance of the class. This allows you to call other class methods or access class-level properties directly without explicitly prefixing them with the class name.

Protocol Conformance

When a class conforms to a protocol that requires a type method (defined in the protocol using the static keyword), the class can satisfy this requirement using either a static func or a class func. Using class func satisfies the requirement while preserving the ability for subclasses to override the implementation.
Tired of Poor Swift Skills? Fix That With Deep Grasping!Learn More