tailor
tailor

Reputation: 665

Strange behaviour of Swift Closure

As the apple described in swift documentation that closures are reference type. So every time when I assign a closure to another reference variable then only reference will be copied. I tried below code and here I found a strange behaviour of swift closures. Here I created an object of MyClass and assigned It to obj. And this object is captured by closure which is referred by cls1, cls2 and cls3. When I call this method, then I get retain count of MyClass object is 5. But if closures are reference type only retain count of closure object should increase not the MyClass object but here retain count of MyClass object is increased.

class ABC{

        class MyClass{}

        static func get(){
            let obj: MyClass = .init()

                let cls1: (()->Void) = {
                    print(obj)
                }
                let cls2 = cls1
                let cls3 = cls1
                let count = CFGetRetainCount(obj)
                print(count)
        }
}

Upvotes: 0

Views: 86

Answers (1)

Duncan C
Duncan C

Reputation: 131491

Firstly, you can't reliably use retain counts to track object ownership. There are too many complicating factors that are outside of your awareness or control.

Second, you forget that closures capture objects from their enclosing scope.

Upvotes: 1

Related Questions