Problem of circular reference between Class and Struct

Code examples are as follows:

class ClassA {
    var struct_b: StructB?
    deinit {
        print("ClassA deinit")

struct StructB {
    var class_a: ClassA?

        let classA = ClassA()
        var structB = StructB()
        /// First case
        ///     classA.struct_b = structB
        ///     structB.class_a = classA
        ///     // Prints "ClassA deinit"
        ///     // classA normal release
        /// Second case
        ///     structB.class_a = classA
        ///     classA.struct_b = structB
        ///     // Prints Nothing,
        ///     // classA cannot release, why?
1 Like

I think one of the references must be marked weak, generally a child’s reference back to a parent data structure.

1 Like

I'm a little curious about why the first case doesn't need to be marked weak

In the second case, you're giving classA a reference to itself via the struct, so you have a reference cycle that prevents classA from deallocating. The first case works differently because you assign the struct before you assign the reference to it, so classA never has a reference to itself. Maybe you're getting tripped up by the fact that structs assign by copy?


I forgot the characteristics of value types.
I'm so stupid :crazy_face:

Never say that of yourself.

I have been developing software for around 30 years and I still make miss obvious things.

I went to university, to learn software development, at the tender age of 37. In those days, one of the languages we were taught was C and it took me a week to grasp hold of the principles of pointer indirection. Fortunately, I had an excellent auto and, when I didn't get it the first time, she explained it in another way, then another way, etc. Once I grasped it, I was, like, "but that's so stupidly simple".

No matter what some folks say, programming is hard, until you get to grips with some of the absolute fundamentals.

Oh, and if you are debugging, make sure that the debugger doesn't hold any references to something :wink:


Thank you very much
Recently, I really like swift programming language, but I don't know how to master the programming skills.
Please recommend some good ways to learn it.