Sobes.tech
Junior

What is the static keyword in Swift?

sobes.tech AI

Answer from AI

static is used to create properties and methods that belong to the type itself (class, struct, enum), rather than to a specific instance of that type. They are accessible directly through the type name.

  • Type Properties: Store values shared across all instances of the type.
  • Type Methods: Perform functions related to the type itself.

Example:

struct MyStruct {
    static var typeProperty: Int = 0 // Type property

    static func typeMethod() { // Type method
        print("This is a type method")
    }
}

// Accessing static members through the type name
MyStruct.typeProperty = 10
MyStruct.typeMethod()

In classes, you can also use the class keyword instead of static to create type methods. The difference is that class methods can be overridden in subclasses, whereas static methods cannot.

static members are stored in memory only once for the entire type.