Skip to content

Instantly share code, notes, and snippets.

@5sw
Last active January 8, 2018 19:05
Show Gist options
  • Save 5sw/819bdae89fb6e5ef21355adf982554f8 to your computer and use it in GitHub Desktop.
Save 5sw/819bdae89fb6e5ef21355adf982554f8 to your computer and use it in GitHub Desktop.
Shows how to break retain cycles
class A {
var b: B?
deinit {
print("A being deallocated")
}
}
class B {
var a: A?
deinit {
print("B being deallocated")
}
}
@discardableResult
func makeCycle() -> A {
let a = A()
let b = B()
b.a = a
a.b = b
return a
}
weak var a: A? = makeCycle()
print(a == nil ? "A is gone" : "A exists")
print("Setting a.b to nil")
a?.b = nil
print(a == nil ? "A is gone" : "A exists")
A exists
Setting a.b to nil
B being deallocated
A being deallocated
A is gone
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment