Junior
What is the static keyword in Swift?
sobes.tech AI
Answer from AI
The static keyword in Swift is used to declare properties or methods that belong to the type (class, struct, enum), rather than to an individual instance of that type.
Usage:
- Type Properties: Store values shared across all instances of the type. Accessible via the type name.
- Type Methods: Called on the type itself, not on an instance. Do not have access to instance properties (
self).
Differences from class (for classes):
staticproperties and methods cannot be overridden in subclasses.classmethods in classes can be overridden in subclasses usingoverride.staticmethods cannot be overridden.
Examples:
struct MyStructure {
static let typeConstant = 10 // Static property (constant)
var instanceVariable = 5
static func typeMethod() { // Static method
print("This is a static method")
// No access to instanceVariable
}
func instanceMethod() { // Instance method
print("This is an instance method")
print(instanceVariable) // Access to instance properties
MyStructure.typeMethod() // Can call static method
}
}
class MyClass {
static var typeVariable = "Static" // Static property (variable)
var instanceProperty = "Instance"
static func staticMethod() { // Static method
print("Class static method")
}
class func classMethod() { // Class method that can be overridden
print("Class method (class)")
}
func instanceMethod() { // Instance method
print("Class instance method")
}
}
// Access to static members
print(MyStructure.typeConstant)
MyStructure.typeMethod()
print(MyClass.typeVariable)
MyClass.staticMethod()
MyClass.classMethod()
// Access to instance members requires creating an instance
let myStruct = MyStructure()
print(myStruct.instanceVariable)
myStruct.instanceMethod()
let myClass = MyClass()
print(myClass.instanceProperty)
myClass.instanceMethod()
Usage:
Often used for:
- Global settings or data related to the type.
- Factory methods.
- Helper functions that do not depend on the instance state.