Reputation: 1263
I am unable to visualise the working of initializers in Swift. For this example from the official documentation.
struct Fahrenheit{
var temp : Double
init(){
temp = 32.0
}
}
var f = Fahrenheit()
print(" \(f.temp)")
//Prints 32.0
Here's what I understood till now, PLEASE correct me when i am wrong:
What i am unable to understand is that what is
init(){
temp = 32.0
}
Upvotes: 3
Views: 107
Reputation: 168
It is definitely important to deeply understand the process of creation of object (as an instance of a class or an instance of the struct). Objects are created based on a template defined in class or struct, in a "space" I like to name as "Object space". So, the object is the instance of struct Fahrenheit in an "Object space" and you could try to see it (visualize) as a balloon. The variable f is a reference to this object and it is been used as a tool to access this balloon (object, instance). I suggest you to take a look to Apple's documentation:
Here you can see this:
And - In my opinion, it is a good way how to visualize objects and references to objects.
So, when the system executes: var f = Fahrenheit(), first - it makes an balloon in Object space, it invokes initialiser (implicit or explicit) to set initial values, than it makes an reference (f) - that points to the just-borned-object.
So:
init(){
temp = 32.0
}
does not make an effect to - f, it makes an effect inside of object (balloon), and f is been uses to access to the balloon. (If there is no reference, the ARC will kill the object)
Upvotes: 3