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?
You can't call methods on self before all non-optional instance variables are initialized. There are several ways to go around that.
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()
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"
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With