How to pass a local function to another object during init?

前端 未结 3 1296
悲&欢浪女
悲&欢浪女 2021-01-29 11:09

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

<
3条回答
  •  心在旅途
    2021-01-29 11:38

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

提交回复
热议问题