deinit is not being called. Help me fix this

354 views Asked by At
class MyClass {
    func greeting() {
        answer += "Hello, World!"
    }
}

class Handler {
    var closure: (() -> Void)?
    let obj = MyClass()
    
    func setupClosure() {
        closure = {
            self.obj.greeting()
        }
    }
    
    deinit {
        answer += "Handler is being deinitialized."
    }
}

var answer: String = ""
func handlerDeinitialization() -> String {
    var handler: Handler? = Handler()
    handler!.setupClosure()
    handler!.closure!()
    handler = nil
    return answer
}

print(handlerDeinitialization())

My expected answer is "Hellow, World! Handler is being deinitialized." How to fix this? I want to change one line of code only, not the whole one.

2

There are 2 answers

2
matt On

Rewrite:

    closure = { [weak self] in
        if let self = self {
            self.obj.greeting()
        }
    }

(Note that I changed more than one line. But my answer is a huge clue towards how to do it by changing just one line.)

2
pushpank On
closure = { [unowned self] in
        self.obj.greeting()
}

for one line solution