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.
-
staticis 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. -
classis 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.