Abhishek Biswas Abhishek Biswas - 1 year ago 92
Swift Question

Understanding to visualize swift initializers

I am unable to visualise the working of initializers in Swift. For this example from the official documentation.

struct Fahrenheit{
var temp : Double
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:

  1. struct is a value type.

  2. variable temp is a stored property that stores values inside the memory space where the struct is defined (in memory).

  3. when we create a variable 'f' is an instance(object) copy of the Structure Fahrenheit is made in another memory space having the same properties.

What i am unable to understand is that what is

temp = 32.0

  1. doing to the instance f.

  2. When do we use intializers in general. (Main purpose : using an example).

  3. Also the difference between functions, closures and initializers, how they are stored in memory?

Answer Source

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:

Suggestion, how to visualize it...

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.


      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)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download