Skip to content

Instantly share code, notes, and snippets.

@mredig
Created January 16, 2021 01:01
Show Gist options
  • Save mredig/ee11a8207ff09ca1b5ab42aa5398b967 to your computer and use it in GitHub Desktop.
Save mredig/ee11a8207ff09ca1b5ab42aa5398b967 to your computer and use it in GitHub Desktop.
an example of an easy accident waiting to happen
//: Playground - noun: a place where people can play
import Foundation
class Bar {
let doingSomething: () -> Void
init(doingSomething: @escaping () -> Void) {
self.doingSomething = doingSomething
}
}
class Foo {
var barSource: Bar!
init() {
// creates strong reference (resulting in retain cycle)
barSource = Bar(doingSomething: anImplementationDoingSomething) // <-- this is what I'm talking about
// creates a weak reference (fixing it)
// barSource = Bar(doingSomething: { [weak self] in
// self?.anImplementationDoingSomething()
// })
barSource.doingSomething()
}
func anImplementationDoingSomething() {
print("it did!")
}
deinit {
print("done with foo")
}
}
func runloopSimulator() {
_ = Foo()
}
runloopSimulator()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment