As the name says Initialization. Initializers are declared to set the initial values of the type when any object of type gets initialized. Initializers are declared using the the syntax
init() {…}
you can also pass parameters to the initializers. So As the Swift programming enforces one simple rule
“Every value must be initialized before it is used”
Only exception to the above rule is optionals where we default their vale to nil.
So what the above rule means? Does it mean that I cannot write something like
var someString : String
No, It means before you access any value it must be initialized in every possible branch of the execution of the code. If you don’t do it you will get a compile time error. Initializers have the responsibility to fully initialize an instance.
Initializers in Structure
So if you have a structure like this
struct Person
{
var firstName : String
var LastName: String
init(first: String, last: String)
{
firstName = first
lastName = last
}
}
- Say you forgot to initialize the firstName in the initiazer, than compiler will generate a compile time error.
- Also if you try to call any method before initializing all the variables in the struct, you will get a compile time error.
- you can write initializers for Structures and Classes both.
Memberwise Initializer
What if you do not specify any Initializer to the struct or class?
Swift Compiler provide you with a Memberwise initializer. So for the above structure if you do not have the initializer declared you can still initialize the values by saying