perhapsmaybeharry perhapsmaybeharry - 1 month ago 10x
Swift Question

Recursive type definitions in Swift

I have encountered what would seem like an extremely simple issue to solve, and I think I may be missing something.

The program crashes when attempting to create a recursive variable (?) with the typed to a class while being a member of the said class. For example:

class A {
var x: A

init() {
x = A()

Checking the crash log suggests a recursion of sorts, with
being called infinitely.

Is there a proper method/syntax to solve this sort of problem, given that I need the variable
to be typed to class
, and the initializer must initialize variable
to class


It's obvious that at some step you should left property x uninitialized. So, thats better to declare it as Optional, and initialize it after instance was created:

class A {
    var x: A?

let mainObject = A()
let nestedObject = A()
mainObject.x = nestedObject