Junior — Middle
Is it possible to set initial values for structure fields immediately upon its declaration?
sobes.tech AI
Answer from AI
In Swift, you can assign initial values to structure fields directly at the point of declaration, which eliminates the need to write a custom initializer if the default values are suitable.
Example:
struct User {
var name: String = "Unknown"
var age: Int = 0
}
let user = User() // name will be "Unknown", age — 0
If all fields have default values, the compiler will automatically generate a parameterless initializer.
You can also combine fields with default values and without, in which case a custom initializer or a synthesized one with parameters will be needed.
Thus, yes, you can immediately assign initial values to structure fields at the time of its declaration.