Sean Sean - 4 months ago 17
iOS Question

Swift Initialization - Why are multiple init functions being called?

Here's is my class with override inits

class BottomView: UIView {

// MARK: - initilization

override init() {
println("init")
super.init()
setup()
}

override init(frame: CGRect) {
println("init frame")
super.init(frame: frame)
setup()
}

required init(coder aDecoder: NSCoder) {
println("init decoder")
super.init(coder: aDecoder)
setup()
}

func setup() {
println("setup")
}
}


I then initialize in my ViewController with the following code

class ViewController: UIViewController {

let bottomView = BottomView()

override func viewDidLoad() {
super.viewDidLoad()

// Do any additional setup after loading the view, typically from a nib.

bottomView.frame = CGRectMake(0.0, self.view.frame.height/2.0, self.view.frame.width, self.view.frame.height/2.0)
bottomView.autoresizingMask = UIViewAutoresizing.FlexibleWidth | UIViewAutoresizing.FlexibleHeight | UIViewAutoresizing.FlexibleTopMargin
self.view.addSubview(bottomView)

}
}


And my output is

init
init frame
setup
setup


So my question is, why is init(frame:) being called?

Answer

super.init() calls self.init(frame:...). Essentially, it's just their way of saying that frame is optional; if you don't pass it, they assign a frame of (0,0,0,0).

func init() {
  self.init(frame:CGRectMake(0,0,0,0));
}
Comments