Created
December 24, 2020 09:12
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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