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

后端 未结 7 1175
旧时难觅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:47

    Assign myImageView in both the init() methods based on a single image create function. As such:

    self.myImageView = self.createMyImageView ();
    

    For example, like such:

    class Bar : Foo {
        var x : Int?
        func createX () -> Int { return 1 }
        init () {
            super.init ()
            self.x = self.createX ()
        }   
    }
    

    Note the 'optional' use at Int?

提交回复
热议问题