'Use of self in method call before super.init initializes self', can't init properties through a method call

后端 未结 1 1035
南方客
南方客 2020-12-11 00:53

I\'m curious is there is anyway to call a method inside your init method that sets instance properties of the class. Essentially I just have a class that sub-classes UIView

1条回答
  •  暖寄归人
    2020-12-11 01:46

    Form documentation:

    Swift’s compiler performs four helpful safety-checks to make sure that two-phase initialization is completed without error:

    Safety check 1 A designated initializer must ensure that all of the properties introduced by its class are initialized before it delegates up to a superclass initializer.

    You need to set value for instance variable before you call super.init() And after this action you will access to call instance methods. In your case you can do this:

    override init (frame : CGRect) {
        self.collectionView = UICollectionView()
        super.init(frame : frame)
        // Now you can call method
        self.someMethod()
    }
    

    ADD for question's EDIT:

    You can't call method before super.init() call because of safety reasons. If you will do it then your method can use some properties which have not yet been initialized in the parent class

    0 讨论(0)
提交回复
热议问题