Keep loop between class and structure

Assuming I have the 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, this would mean a conservation cycle. However, it is not clear to me how the differences between classes and structures apply to the above example. Could this cause a save loop or is it safe code due to the use of a structure?

+4
source share
3 answers

Yes, you have a save cycle.

y.propertyOfTypeX = x

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

therefore

y.propertyOfTypeX?.propertyOfTypeY === y

occurs. What you have is essentially the same as

class Y {
    var propertyOfTypeY: Y?
}

var y = Y()
y.propertyOfTypeY = y

, propertyOfTypeY a struct X ( x y).

+7

TL; DR , !

struct X {
    let propertyOfTypeY: Y
}

class Y {
    var propertyOfTypeX: X?

    deinit {
        print("I was deinit'ed")
    }
}

do {
    let y = Y()
    let x = X(propertyOfTypeY: y)
    y.propertyOfTypeX = x
}
// y and x should be dealloc'ed here, because the "do scope" ends

y.propertyOfTypeX = x I was deinit'ed, , deinit .

, .

+5

enter image description here .

: unowned weak

struct X {
    unowned let propertyOfTypeY: Y
}

class Y {
    var propertyOfTypeX: X?

    deinit {
        print("Y deallocated")
    }
}

do {
    let y = Y()
    let x = X(propertyOfTypeY: y)
    y.propertyOfTypeX = x
}
0

Source: https://habr.com/ru/post/1671626/


All Articles