Ios – Swift. Use of ‘self’ in method call before all stored properties are initialized

iosswift

I have a class

class ChartView: UIView
{
  class: DotView {
    let circleView1: UIView
    let circleView2: UIView

    init (view: UIView)
    {
      self.view = view
      self.circleView1 = self.buildCircle(some rect here)
      self.circleView2 = self.buildCircle(some rect here)

    func buildCircle(rect: CGRect) -> UIView
    {
       let dotView = UIView(frame: rect)
       dotView.backgroundColor = UIColor.whiteColor()
       dotView.layer.cornerRadius = dotView.bounds.width / 2
       self.view.addSubview(dotView)
       return dotView
    }
  }
}

But I got this error:
Use of 'self' in method call 'buildCircle' before all stored properties are initialized

So I just want to create objects in some method and then assign it to the stored properties. How can I fix my code?

Best Answer

You can't call methods on self before all non-optional instance variables are initialized. There are several ways to go around that.

  1. Change properties to optionals or implicitly unwrapped optionals (not recommended)
  2. Make the buildCircle() method static or just a function in the file and call the addSubview() for all the circles after all of the properties were initialized and you called super.init()
  3. etc. You just have to avoid calls to self before the class was initialized.
Related Topic