Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
import Foundation
import XCTest
class Ref {
var success = false
}
class Foo {
private let ref: Ref
private var handler: (()->Void)?
func noop(){}
init(ref: Ref) {
self.ref = ref
}
func createCycle(){
handler = { self.noop() }
}
func createCaptureList(){
handler = { [unowned self] in self.noop() }
}
func directAssignment(){
handler = noop
}
deinit {
ref.success = true
}
}
class CaptureSelfTests: XCTestCase {
let ref = Ref()
func testDeinitWorks() {
var subject = Optional(Foo(ref: ref))
print(subject) //just to avoid "subject not used" warning.
subject = nil
XCTAssert(ref.success)
}
func testRetainCycle() {
var subject = Optional(Foo(ref: ref))
subject?.createCycle()
subject = nil
XCTAssertFalse(ref.success)
}
func testCaptureList() {
var subject = Optional(Foo(ref: ref))
subject?.createCaptureList()
subject = nil
XCTAssert(ref.success)
}
func testDirectAssignment() {
var subject = Optional(Foo(ref: ref))
subject?.directAssignment()
subject = nil
XCTAssert(ref.success) //Uh-oh!
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment