How to implement two inits with same content without code duplication in Swift?

后端 未结 7 1172
旧时难觅i
旧时难觅i 2020-12-01 00:10

Assume a class that is derived from UIView as follows:

class MyView: UIView {
    var myImageView: UIImageView

    init(frame: CGRect) {
               


        
7条回答
  •  我在风中等你
    2020-12-01 00:37

    Does it necessarily have to come before? I think this is one of the things implicitly unwrapped optionals can be used for:

    class MyView: UIView {
        var myImageView: UIImageView!
    
        init(frame: CGRect) {
            super.init(frame: frame)
            self.commonInit()
        }
    
        init(coder aDecoder: NSCoder!) {
            super.init(coder: aDecoder)
            self.commonInit()
        }
    
        func commonInit() {
            self.myImageView = UIImageView(frame: CGRectZero)
            self.myImageView.contentMode = UIViewContentMode.ScaleAspectFill
        }
    
        ...
    }
    

    Implicitly unwrapped optionals allow you skip variable assignment before you call super. However, you can still access them like normal variables:

    var image: UIImageView = self.myImageView // no error

提交回复
热议问题