How to pass a local function to another object during init?
I did the below, but got \'self\' captured by a closure before all members were initialized
if it's an option for you I'd suggest making the dismiss
block not part of the init but rather an optional var on the ContentView.
My solution would look kind of like:
ContentView
class ContentView: UIView {
var dismiss: (() -> Void)?
init(drawView: UIView) {
super.init(frame: .zero)
}
...
}
You could also indicate the dismiss block will always be there by replacing the ?
with an !
(var dismiss: (() -> Void)!
) so you don't have to unwrap it when calling but I wouldn't suggest that as it's not compile time safe and so not what you really want.
ContextViewController
class ContextViewController: UIHostingController {
let drawViewWrapper: ContentView
lazy var selfDismiss: () -> Void = { [unowned self] in
self.dismiss(animated: true)
}
init(drawView: CustomDrawView) {
self.drawViewWrapper = ContentView(drawView: drawView)
super.init(rootView: self.drawViewWrapper)
self.drawViewWrapper.dismiss = selfDismiss
}
...
}