How to initialize properties that depend on each other

后端 未结 4 963
心在旅途
心在旅途 2020-11-21 05:10

I want a picture to move to the bottom. If I press a button the pic should move down by 1.

I added the picture and a button:

var corX = 0
var corY =         


        
4条回答
  •  别跟我提以往
    2020-11-21 05:56

    @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.

提交回复
热议问题