Swift Using "self" in a method call before all stored properties are initialized

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: Using "self" in a call to the "buildCircle" method before initializing all stored properties

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

+4
source share
3 answers

You cannot invoke methods yourself before all optional instance variables are initialized. There are several ways around this.

  • Change the properties to additional or implicitly expanded options (not recommended)
  • buildCircle() addSubview() , , super.init()
  • ... .
+8

:

class MyClass: NSObject {
    var prop: String = ""

    override init() {
        super.init()
        self.setupMyProperty()
    }

    func setupMyProperty() {
        prop = "testValue"
    }
}


class MyClass1: NSObject {
    var prop: String = ""

    override init() {
        prop = MyClass1.setupMyProperty()
        super.init()
    }

    class func setupMyProperty() -> String{
        return "testValue"
    }
}
+2

willMoveToSuperview. ChartView, :

override func willMoveToSuperview(newSuperview: UIView?) {
      self.circleView1 = self.buildCircle(some rect here)
      self.circleView2 = self.buildCircle(some rect here)
}
0
source

Source: https://habr.com/ru/post/1651791/


All Articles