-1

I got some issue with closure/struct/capturing properties.

I can't really explain the architecture but i need to have something like this:

class ControllerAAA {
    struct Events {
        var userDidSelect(_ controller: Controller) -> ()?
    }
}

class ControllerBBB {
    var foo: Foo

    var events: ControllerAAA.Events(userDidSelect: {
        (controller: Controller) -> ()? in
         // Here i need foo. Self mean the Block not the Controller
    })

    // Then i will passed events when i call ControllerAAA and ControllerAAA will use events.userDidSelect(...) when he is done.
}

Is it possible to reach “self” in closure that is in struct constructor defined in class?

Nek
  • 73
  • 8
  • Have you shown your complete set of code? It looks like you are using an `init` on your `ControllerAAA.Events` call that is not shown. Perhaps the label in your instantiation is supposed to read `userDidSelect:` instead of `userDidCancel:`? – Scott Thompson May 11 '17 at 15:30
  • Sorry the userDidCancel was an error. Its actually not at all real code just the architecture. – Nek May 11 '17 at 15:33

1 Answers1

0

At the point you are defining your callback block, you are in the lexical scope of the class, not an instance of the class. To solve this, you are going to have to initialize your callback in the context of an instance method.

I might try something like:

enum ControllerAEvent {
    case userDidSelect((_ controller: Controller) -> ())
}

class ControllerBBB {
    var foo: String

    var events: ControllerAEvent

    init() {
        events = .userDidSelect({
            (controller: Controller) -> () in

            Print(self.foo)
        })
    }
    // Then i will passed events when i call ControllerAAA and ControllerAAA will use events.userDidSelect(...) when he is done.
}
Scott Thompson
  • 22,629
  • 4
  • 32
  • 34
  • I'am close to be able to test it. But actually got another probleme, how can I call ControllerAEvent.userDisSelect(...) ? Here is the error : Enum element 'userDidSelect cannot be referenced as an instance member – Nek May 11 '17 at 16:53
  • ` func fireEvent(event: ControllerAEvent) { switch event { case .userDidSelect(eventCallback) : eventCallback(self) } }` – Scott Thompson May 11 '17 at 19:04
  • Not working :/ I will try to do it somehow. Thanks for help ! – Nek May 12 '17 at 07:59