Chapter 24, page 394 - closure passing self

Hi, I have question when creating lazy variable in TasksViewModel. The books says

lazy var editAction: Action<TaskItem, Void> = { this in
return Action { task in
let editViewModel = EditTaskViewModel(
task: task,
coordinator: this.sceneCoordinator,
updateAction: this.onUpdateTitle(task: task)
return this.sceneCoordinator.transition(to:
Scene.editTask(editViewModel), type: .modal)
} }(self)

  1. Can somebody explain why can we write a closure like above, passing self into a closure as this?
  2. If I remove closure passing in self, just replace this with self, the compiler will yell at me with an error:

Closure cannot implicitly capture a mutating self parameter

Why is this happening?

maybe this is the solution:
ios - Closure cannot implicitly capture a mutating self parameter - Stack Overflow

cause Action here can escape in lifetime of self(struct of TasksViewModel), maybe passing in self as this inside closure can avoid this problem?

@yoxisem544 when you define a lazy var, you define a closure that is being dynamically called the first time the variable is being accessed, and must return a value for this variale.

Since this is an instance variable, self exists at this time and we can pass it to the closure. The trick I used here is that, defining a closure that takes a parameter, I can pass this parameter in the call.

I could also have moved all this to a function and written:

lazy var editAction: Action<TaskItem, Void> = makeEditAction()

func makeEditAction() -> Action<TaskItem, Void> {
// ...

This topic was automatically closed after 166 days. New replies are no longer allowed.