perhapsmaybeharry perhapsmaybeharry - 2 months ago 12
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
init()
being called infinitely.

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

Answer

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
Comments