Value type cannot have a stored property that recursively contains it

Andrew Lundy
1 min readDec 6, 2021

In Swift, this error is thrown when trying to build a value type that recursively calls itself. This is not possible because value types are fixed structures. This means they are stored in a fixed place in memory, and the compiler expects to be able to compute the value of fixed structures at compile time.

With a value type that recursively calls itself, the compiler will never be able to compute the values of that recursively called reference to the type because it is not initialized before the compile time. The compiler must know how much space the properties of a value type are going to contain.

What’s the Fix?

To answer this, one must know where structures are stored in memory.

Structures are stored on the stack, compared to the heap. The stack is used for static memory allocation, whereas the heap is used for dynamic memory allocation. The stack allocates memory at compile-time, which is why a structure’s values are expected to be known; so the memory can be properly allocated.

The fix is to use a class instead of a structure.

A class is stored on the heap, which again, is used for dynamic memory allocation. The heap allocates memory at runtime, therefore, the Swift compiler doesn’t need to know how much space the values will take up.

For more on this subject, check out this Stack Overflow thread: https://stackoverflow.com/a/42453109/7188134.

--

--