Build error when trying to override an initializer in Xcode 6.3 Beta 3

后端 未结 3 651
醉酒成梦
醉酒成梦 2020-12-06 00:42

The following code shows build error in Xcode 6.3 Beta 3. The code works in Xcode 6.2 and Xcode 6.3 Beta 2.

class MyView: UIView {
  overrid         


        
相关标签:
3条回答
  • 2020-12-06 01:30

    An additional way of resolving is to provide a default argument for the frame parameter of the UIView

    override init(frame: CGRect = CGRectZero) {
         super.init(frame: frame)
         // custom code
    }
    
    0 讨论(0)
  • 2020-12-06 01:32

    A designated initializer of a subclass needs to call the designated initializer of Superclass. A convenience initializer can only call another convenience initializer or a designated initializer of that class.

    init() is a convenience initializer for UIView, if you subclass UIView you should call its designated initializer which is init(frame: frame)

    override init() {
    super.init(frame: frame)
    // Some init logic ...
    }
    

    EDIT: Apparently in Beta 3, UIView doesn't have convenience initializer called as init, so you need to remove the override keyword too, now this is a designated initializer so you need to call superclass's designated initializer

    init() {
    super.init(frame: frame)
    // Some init logic ...
    }
    

    EDIT: Although this works but I think a better way to write this would be:

    convenience init() {
    self.init(frame:CGRectZero)
    }
    

    Source:Swift documentation

    Rule 1 A designated initializer must call a designated initializer from its immediate superclass.

    Rule 2 A convenience initializer must call another initializer from the same class.

    Rule 3 A convenience initializer must ultimately call a designated initializer.

    0 讨论(0)
  • 2020-12-06 01:32

    swift3 working : @Andrea comment

    try to change super.init() in self.init()

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