Search code examples
swiftmemory-leaksretain-cycle

Retain cycle between class and struct


Assuming I have following code:

struct X {
    let propertyOfTypeY: Y
}

class Y {
    var propertyOfTypeX: X?
}

let y = Y()
let x = X(propertyOfTypeY: y)
y.propertyOfTypeX = x

If these were both classes, then it would mean a retain cycle. However it's not clear to me how the differences between classes and structs apply to the example above. Will it cause a retain cycle, or is it a safe code because of the usage of struct?


Solution

  • Yes, you have a retain cycle.

    y.propertyOfTypeX = x
    

    copies the value x to y.propertyOfTypeX, including the property x.propertyOfTypeY which is a reference to y.

    Therefore

    y.propertyOfTypeX?.propertyOfTypeY === y
    

    holds. What you have is essentially the same as

    class Y {
        var propertyOfTypeY: Y?
    }
    
    var y = Y()
    y.propertyOfTypeY = y
    

    only that propertyOfTypeY is part of a struct X (and that x holds an additional reference to y).