Skip to main content
A static method in Swift is a type-level method associated with the type itself rather than an instance of that type. It is invoked directly on the type’s namespace and operates independently of any specific object instance, meaning it cannot access instance properties or instance methods.

Syntax and Declaration

Static methods are declared using the static keyword preceding the func keyword. They can be defined within structures, enumerations, classes, and actors.

Execution Context and self

Within the body of a static method, the implicit self property refers to the type itself, rather than an instance of the type. This allows a static method to call other static methods or access static properties directly without prefixing them with the type name.
Because there is no instance context, attempting to access an instance property or instance method from within a static method will result in a compile-time error.

static vs. class Methods

When working with Swift classes, type methods can be declared using either the static keyword or the class keyword. The distinction dictates whether the method participates in dynamic dispatch and overriding.
  • static func: Statically dispatched. Subclasses cannot override this method. It is functionally equivalent to final class func.
  • class func: Dynamically dispatched. Subclasses are permitted to override the method implementation.

Protocol Requirements

When defining a protocol that requires a type-level method, you must always use the static keyword in the protocol declaration.
When a type conforms to this protocol, it satisfies the requirement based on its type paradigm:
  • Structures and enumerations must implement it using static.
  • Classes can implement it using either static (if overriding should be prevented) or class (if overriding should be allowed).
Tired of Poor Swift Skills? Fix That With Deep Grasping!Learn More