Swift Structs: How Custom Initializers and 'self' Give You More Control
In Swift, structs automatically receive a memberwise initializer that accepts each property as a parameter, but developers can write custom initializers for greater control over how instances are set up. Custom initializers use the 'self' keyword to distinguish between a struct's own properties and incoming parameters that share the same name, making code cleaner and less ambiguous. Unlike regular functions, initializers have no 'func' keyword and no return type, yet Swift strictly requires that every property must be assigned a value before the initializer completes. Failing to assign even one property will prevent the code from compiling. The real advantage of custom initializers is flexibility — for example, a property can be automatically assigned a random or computed value rather than requiring the caller to supply it.
This is an AI-generated summary. ShortSingh links to the original source for the complete article.
Discussion (0)
Log in to join the discussion and vote.
Log in