-3

I'm trying to prevent a function from being called concurrently at the same time. To test this out, I have purposely called both functions in viewdidload and viewwillappear. When i load the application it only gets called once. But when I switch views and return back to the controller, "viewwillappear" doesn't call the function? Why is this happening. I need viewwillappear to call the function.

lazy var executeOnce: () -> Void = {
    print("hrlllo ")
    doSomething()
    return {}
}()


override func viewDidLoad() {
    super.viewDidLoad()

    executeOnce()

}


override func viewWillAppear(_ animated: Bool) {
    executeOnce()

}
rmaddy
  • 307,833
  • 40
  • 508
  • 550
  • So, it seems correct for that func not being called since it's already called in `viewDidLoad`? I'm not sure I get your question. Also, you forgot to call super.viewWillAppear(animated). – aunnnn Sep 27 '18 at 23:01

1 Answers1

-1

executeOnce in your code is a stored property. When it is called in viewDidLoad(), the closure in its definition

{
    print("hrlllo ")
    doSomething()
    return {}
}

is evaluated.

In your case, you are returning an empty closure {} and then executing it with (), which equal to void or doing nothing. This value Void is the one stored in your property executeOnce.

So, whenever you call executeOnce(), the initial closure is not evaluated, but is the value stored in executeOnce which is called, which is Void. And thus, nothing will be executed.

The keyword lazy will only delay the execution of the closure until needed. It has nothing to do with the closure evaluated only once.

ielyamani
  • 16,529
  • 10
  • 46
  • 78