Cannot use instance member in property initializer

I wrote a custom UIView and I found a strange problem. I think this is due to a very fundamental concept, but I just don’t understand it, sigh .....

 class ArrowView: UIView { override func draw(_ rect: CGRect) { let arrowPath = UIBezierPath.bezierPathWithArrowFromPoint(startPoint: CGPoint(x:bounds.size.width/2,y:bounds.size.height/3), endPoint: CGPoint(x:bounds.size.width/2, y:bounds.size.height/3*2), tailWidth: 8, headWidth: 24, headLength: 18) let fillColor = UIColor(red: 0.00, green: 0.59, blue: 1.0, alpha: 1.0) fillColor.setFill() arrowPath.fill() } } 

this code works fine, but if I grab this line from the undo function, it does not compile. The error says that I cannot use the bounds property.

 let arrowPath = UIBezierPath.bezierPathWithArrowFromPoint(startPoint: CGPoint(x:bounds.size.width/2,y:bounds.size.height/3), endPoint: CGPoint(x:bounds.size.width/2, y:bounds.size.height/3*2), tailWidth: 8, headWidth: 24, headLength: 18) 

Unable to use instance member bounds in property initializer; Property initializers start before "self".

I do not understand why I can not use these restrictions from func draw

+5
source share
1 answer

So, if we decode the error message, you can understand what is wrong. He says property initializers run before self is available , so we need to customize what we do, because our property depends on boundaries that belong to ourselves. Let's try using a lazy variable. You cannot use borders in let, because they do not exist when this property is created, because it belongs to itself. So init init is not completed yet. But if you use lazy var, then itself and its property borders will be ready by the time you need it.

 lazy var arrowPath = UIBezierPath.bezierPathWithArrowFromPoint(startPoint: CGPoint(x: self.bounds.size.width/2,y: self.bounds.size.height/3), endPoint: CGPoint(x: self.bounds.size.width/2, y: self.bounds.size.height/3*2), tailWidth: 8, headWidth: 24, headLength: 18) 
+7
source

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


All Articles