How to initialize properties that depend on each other

@MartinR has pointed out the major issue here:

var corX = 0
var corY = 0
var panzer = UIImageView(frame: CGRectMake(corX, corY, 30, 40))

The problem is that a Swift default initializer cannot refer to the value of another property, because at the time of initialization, the property doesn’t exist yet (because the instance itself doesn’t exist yet). Basically, in panzer‘s default initializer you are implicitly referring to self.corX and self.corY – but there is no self because self is exactly what we are in the middle of creating.

One workaround is to make the initializer lazy:

class ViewController: UIViewController {
    var corX : CGFloat = 0
    var corY : CGFloat = 0
    lazy var panzer : UIImageView = UIImageView(frame: CGRectMake(self.corX, self.corY, 30, 40))
    // ...
}

That’s legal because panzer doesn’t get initialized until later, when it is first referred to by your actual code. By that time, self and its properties exist.

Leave a Comment