Goktug Goktug - 1 month ago 10
Swift Question

Memory Allocation of Primitive Types

I searched this but I couldn't find the answer.

Is memory allocation performed when we declare a variable like this:

var x : Int

or do we also have to initialize it to allocate memory for this variable?

Answer Source

It all depends on how the property is declared. It can also be implementation-dependant or optimized to some other behavior.

The Swift Programming Language (Swift 4) Properties

In general, stored properties are allocated early. Either immediately or sometime before they are used. Lazy properties are allocated when they are accessed. Computed properties are never allocated, they are calculated when they are accessed.

In your example the variable is declared but not initialized or allocated. If you try to use it without setting it to a value you will get this statement from the compiler:

Variable 'x' used before being initialized

Once you assign a value to it then it will be allocated:

var x: Int // declared but not allocated or initialized
x = 10     // allocated and initialized

If it was part of a struct then the whole struct gets allocated at once. The init method takes care of initializing the memory.