Skip to content

Instantly share code, notes, and snippets.

@manmal
Created December 24, 2020 09:12
Show Gist options
  • Save manmal/7ac7c0206795d1c3108f49fe241b19fd to your computer and use it in GitHub Desktop.
Save manmal/7ac7c0206795d1c3108f49fe241b19fd to your computer and use it in GitHub Desktop.
Swift object and struct instances are retained if an empty method of theirs is captured
import Foundation
final class A {
func someMethod() {}
}
struct B {
let a: A
func someMethod() {}
}
struct Capturing {
let closure: () -> Void
}
var capturing: Capturing!
weak var weakA: A?
// Object instance is retained by capturing method...
autoreleasepool {
_ = {
let a = A()
capturing = Capturing(closure: a.someMethod)
weakA = a
}()
}
print(weakA == nil ? "released" : "retained")
// ... and same for a struct instance (we use a object var to find out)
autoreleasepool {
_ = {
let b = B(a: A())
capturing = Capturing(closure: b.someMethod)
weakA = b.a
}()
}
print(weakA == nil ? "released" : "retained")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment