0
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.

Machavity
  • 30,841
  • 27
  • 92
  • 100
David S
  • 55
  • 7
  • Your handler's closure is not necessarily being deinitialized in the deinit of `Handler`. Closures are reference types - they get deinitialized when the last reference to this closure gets deinitialized. Independently of this little nit-pick, you can set the closure's reference in the object to nil at any time. – CouchDeveloper May 12 '21 at 11:17

2 Answers2

3

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.)

matt
  • 515,959
  • 87
  • 875
  • 1,141
  • Thanks for your answer. Honestly, this is a test from CodeSignal. They ask one line of codes to be edited. No more than 1 line. – David S May 13 '21 at 03:14
  • Yes, I see how to do that. But I think they want to know if you see how to do it. My answer is a huge clue; if you know some Swift, or are willing to learn, you will be able to follow where it leads. – matt May 13 '21 at 03:44
1
closure = { [unowned self] in
        self.obj.greeting()
}

for one line solution

pushpank
  • 262
  • 3
  • 9
  • What are the consequences of removing the condition used in the original answer? – Jeremy Caney Oct 09 '21 at 00:40
  • If you are saying about closure = { [weak self] in if let self = self { self.obj.greeting() } } This is the correct answer. But in code signal test they allowed only one line change. So we can use unowned instead of weak. In the case of unowned you don’t need to unwrap the self. – pushpank Oct 10 '21 at 10:40