Reference cycles with value types?

后端 未结 6 1412
太阳男子
太阳男子 2020-12-03 08:34

Reference cycles in Swift occur when properties of reference types have strong ownership of each other (or with closures).

Is there, however, a possibility of havin

6条回答
  •  盖世英雄少女心
    2020-12-03 08:43

    You normally cannot have a reference cycle with value types simply because Swift normally doesn't allow references to value types. Everything is copied.

    However, if you're curious, you actually can induce a value-type reference cycle by capturing self in a closure.

    The following is an example. Note that the MyObject class is present merely to illustrate the leak.

    class MyObject {
        static var objCount = 0
        init() {
            MyObject.objCount += 1
            print("Alloc \(MyObject.objCount)")
        }
    
        deinit {
            print("Dealloc \(MyObject.objCount)")
            MyObject.objCount -= 1
        }
    }
    
    struct MyValueType {
        var closure: (() -> ())?
        var obj = MyObject()
    
        init(leakMe: Bool) {
            if leakMe {
                closure = { print("\(self)") }
            }
        }
    }
    
    func test(leakMe leakMe: Bool) {
        print("Creating value type.  Leak:\(leakMe)")
        let _ = MyValueType(leakMe: leakMe)
    }
    
    test(leakMe: true)
    test(leakMe: false)
    

    Output:

    Creating value type.  Leak:true
    Alloc 1
    Creating value type.  Leak:false
    Alloc 2
    Dealloc 2
    

提交回复
热议问题