0

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)
        }
}
rmaddy
  • 314,917
  • 42
  • 532
  • 579
tailor
  • 680
  • 4
  • 12
  • I don't find anything strange here, you are 'capturing' `obj` inside your closure and passing the reference to `cls2` and `cls3` – Lokesh SN Jul 22 '19 at 17:34
  • `CFGetRetainCount` means nothing. Less than nothing. https://stackoverflow.com/questions/4636146/when-to-use-retaincount You've forgotten about the existence of autorelease, which adds retain counts that will be removed in the near future. If you recompile this code with optimizations, you will likely get a completely different result, but it would still be meaningless. – Rob Napier Jul 22 '19 at 17:45
  • I don't think that's a fair criticism of this question. While we should not base the correct behavior of our programs on implementation details, we can still benefit from understanding those details. – rob mayoff Jul 22 '19 at 17:52

1 Answers1

1

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.

Duncan C
  • 128,072
  • 22
  • 173
  • 272
  • “too many complicating factors that are outside of your awareness or control”—but the point of this question is to learn what those factors are! As for “closures capture objects”—ok, but why does duplicating a reference to a closure increase the reference count of an object captured by the closure? After all, duplicating a reference to a view doesn't increment the reference counts of the view's subviews. – rob mayoff Jul 22 '19 at 18:03
  • @robmayoff You are correct. I just want to know why closure behaves like value type in my code instead of reference type. – tailor Jul 23 '19 at 17:38