Junior — Middle
Is it necessary to assign a value to a static variable at the time of declaration?
sobes.tech AI
Answer from AI
In iOS (Swift or Objective-C), static variables do not necessarily need to be assigned a value at declaration. If no value is assigned:
- For types that support default initialization, the variable will be initialized with the default value (e.g.,
0for numbers,nilfor optionals). - If the variable is declared as
let(constant), then a value must be assigned at declaration.
Example in Swift:
class Example {
static var counter: Int // not necessarily assigned immediately
static var name: String = "Default" // assigned a value
}
// Accessing Example.counter for the first time will cause an error if it is not explicitly initialized before use.
Therefore, although assignment is not mandatory at declaration, the static variable must be initialized before use, otherwise a compile-time or runtime error will occur.