Search code examples
swiftmemory-managementallocationcomputed-properties

Computed property does not require storage allocation


A basic question and might even be stupid, but it's important to me. I don't know the answer and I appreciate your time.

[Issue]:

In Swift, there isn't any storage allocation for computed property, so it's not really a variable You can find this sentence on page 197 of the second chapter of the book iOS Apprentice (5th version)

[Question]:

There isn't any storage allocation for computed property? I don't understand this. There got to be some place in the memory to hold up the data to do the computation, otherwise, how does this even possible? Or, it means to compute the value only being called and to remove/destroy the data after it has handed to the caller, am I in the right direction of this concept?

Thanks


Solution

  • Computed properties are much like functions that take no arguments and return a value. For the lifetime of the execution of a computed property, some memory will temporarily be allocated on the stack, to store the local variables of the computed property.

    In addition to this, the instructions of the computed property have to be stored somewhere in your compiled program. Luckily, you only need one copy of the definition, which can be used for all instances.

    The important point is that there is no per-instance memory required.