简体   繁体   中英

Swift lazy initialization can't conform to the protocol

I declared several UI components in a protocol.

protocol SomeViewContainer {
    var aView: ACustomizedView
    ...
}

class TestViewController: SomeViewContainer {
    var aView: ACustomizedView!

}

The above code won't pass because the compiler doesn't think TestViewController conforms to the protocol.

The aView will be initialized after the data fetched from the remote, so I can't just remove the ! .
In addition, I would prefer to lazy initialzation like the following for some other properties declared in the protocol.

lazy var aView: UIView! = {

    }()

Still Failed to compile. Are there any ideas on how to conform a protocol with lazy initialization?

So two issues, one a property with type ACustomizedView! is not the same as a property with ACustomizedView which is why it doesn't conform

Secondly, you should be able to use lazy. Is that your actual code?

lazy initialization uses a self executing closure, so it'll run the closure code automatically when called and supply the property with what the closure RETURNS

the fact you have nothing inside the closure will cause it to break..

you need to actually return a view from inside the closure

lazy var aView: UIView = {
    let view = UIView()
    // configure view
    return view
}()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM