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

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

    What we need is a common place to put our initialization code before calling any superclass's initializers, so what I currently using, shown in a code below. (It also cover the case of interdependence among defaults and keep them constant.)

    import UIKit
    
    class MyView: UIView {
            let value1: Int
            let value2: Int
    
            enum InitMethod {
                    case coder(NSCoder)
                    case frame(CGRect)
            }
    
            override convenience init(frame: CGRect) {
                    self.init(.frame(frame))!
            }
    
            required convenience init?(coder aDecoder: NSCoder) {
                    self.init(.coder(aDecoder))
            }
    
            private init?(_ initMethod: InitMethod) {
                    value1 = 1
                    value2 = value1 * 2 //interdependence among defaults
    
                    switch initMethod {
                    case let .coder(coder): super.init(coder: coder)
                    case let .frame(frame): super.init(frame: frame)
                    }
            }
    }
    

提交回复
热议问题