A Concise Introduction to Object Initialization in Swift
In computer programming, a class represents an idea.
A Dog class represents the idea of a dog — it’s merely a blueprint that tells you how to create a dog. To turn this “idea of a dog” into “a real dog,” you need a special function called an initializer.
An initializer, whether automatically provided by Swift or explicitly declared with the init keyword constructs an instance of the Dog class in a process known as object initialization.
In the case of our Dog class, this is how a simple idea of a dog is transformed into a real useable dog object.
Let’s see how it works!
Example Class Initializer
class Dog {
}
Dog()
The code begins by declaring a Dog class.
Then the Dog class is called using its name, followed by parentheses. This syntax initializes a new instance of the Dog class so that it becomes a real dog.
The problem, however, is that we can’t yet use this newly initialized dog because we can’t access it.
To do this, let’s assign the instance to a variable named lassie.
var lassie = Dog()
Now, our dog has gone from just an idea dog to a real dog object that we can use in our code.
Initialization is an important part of object-oriented programming (OOP) and the example code in this tutorial uses what's known in Swift as an implicit initializer.