Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift. Use of 'self' in method call before all stored properties are initialized [duplicate]

Tags:

ios

swift

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?

like image 397
Matrosov Oleksandr Avatar asked Aug 19 '16 12:08

Matrosov Oleksandr


2 Answers

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.
like image 57
Piotr Tobolski Avatar answered Sep 19 '22 20:09

Piotr Tobolski


For solving of this issue it is possible to use these approaches:

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"
    }
}
like image 42
Oleg Gordiichuk Avatar answered Sep 19 '22 20:09

Oleg Gordiichuk