Sobes.tech
Junior — Middle

Is it possible for a structure to contain an object of the same structural form inside it?

sobes.tech AI

Answer from AI

Yes, in Swift a structure can contain an object of the same structure, but only indirectly — through optional properties or pointers, to avoid infinite recursion during memory allocation.

Example with an optional property:

struct Node {
    var value: Int
    var next: Node?  // Optional reference to the next node
}

Here, the Node structure contains an optional object of the same type Node. This is often used for building linked lists and other recursive data structures.

You cannot declare a property of the structure type directly without an optional, as this would lead to infinite nesting and a compilation error.