Sobes.tech
Junior — Middle

How to implement behavior similar to static properties or methods in other programming languages in Swift?

sobes.tech AI

Answer from AI

In Swift, the keywords static and class are used to implement behavior similar to static properties or methods in other languages.

  • static is used to declare properties and methods that belong to the type itself (class, struct, or enum), not to an instance. Such properties and methods cannot be overridden in subclasses.

  • class is used for methods and properties in classes that can be overridden in subclasses.

Example:

class MyClass {
    static var staticProperty = "Static property"
    class func classMethod() {
        print("Class method")
    }
}

print(MyClass.staticProperty) // Outputs: Static property
MyClass.classMethod()        // Outputs: Class method

Thus, static and class allow creating properties and methods that exist at the type level rather than the instance level, which corresponds to the concept of static members in other languages.

How to implement behavior similar to static… - sobes.tech