Skip to content

Instantly share code, notes, and snippets.

@eneko
Last active February 8, 2019 17:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save eneko/ad6f8688caf8cea887ca99783c970edf to your computer and use it in GitHub Desktop.
Save eneko/ad6f8688caf8cea887ca99783c970edf to your computer and use it in GitHub Desktop.
Function references and retain cycles
class MyClass {
var foo: () -> Void = {}
init() {
foo = defaultFoo
}
private func defaultFoo() {
print("Foo Bar")
}
deinit {
print("MyClass Released 🎉") // Never gets called, retain cycle
}
}
class MyClassNested {
var foo: () -> Void = {}
init() {
func defaultFoo() {
print("Foo Bar Nested")
}
foo = defaultFoo
}
deinit {
print("MyClassNested Released 🎉") // Gets called
}
}
var normal: MyClass? = MyClass()
var nested: MyClassNested? = MyClassNested()
normal?.foo() // prints: Foo Bar
nested?.foo() // prints: Foo Bar Nested
normal = nil // deinit does not get called
nested = nil // prints: MyClassNested Released 🎉
// Alternatively, this code is simpler, but deinit is called first because the instance is released right away
MyClass().foo() // deinit does not get called
MyClassNested().foo() // deinit gets called
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment