23

I am new with Swift. I inherited a project. I saw it running on a device. However, when I checkout the code and it had many errors. I was able to clear out the errors. However, I run into this one that is baffling me. The project uses xib files as well. Here is the code.

    required init(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }

    override init(frame: CGRect) {
        super.init(frame: frame)
    }

   init(items:NSArray, viewController:AnyObject){
        super.init()
        //itemsArray = items
        itemsArray = items as [AnyObject]
        //commonInit(viewController as UIViewController)
        commonInit(viewController as! UIViewController)
    }

I get the error under the init(items:NSArray, viewController:AnyObject) method/function. The error is pointed at the "super.init()". It states "Must call a designated initializer of the superclass 'UIView' error"

I been searching, googling, asking others and nothing has turned up. Can I get help on fixing this error, or at least why this error happens? I would like understand so I can become a better software developer.

Edit: I would like to thank everyone for their insight and help. I found out the problem is bigger. I did the changes suggested in the super.init(frame: CGRect). I had to change an array property as well which was affecting the init function.

EberronBruce
  • 330
  • 1
  • 3
  • 11

2 Answers2

19

As the error message suggests you can only call the designated initializer of the superclass.

To solve this you need to call : super.init(frame: frame) instead of super.init()

The Tom
  • 2,790
  • 6
  • 29
  • 33
  • 1
    what frame size needs to send in super.init(frame: frame). My view have flexible width and height. – Gurjit Singh Aug 13 '19 at 08:24
  • Well, you can always send a bogus height and width and change it afterwards. Although I would recommend trying to get the right size from the start. If it has a flexible width and height, surely you must know them. – The Tom Aug 13 '19 at 17:30
14

UIView's designated initializers are:

init(frame: CGRect)
init(coder aDecoder: NSCoder)

You're calling super.init() which is an initializer inherited from its superclass NSObject. Use one of those initialises instead as the compiler is suggesting in order to (actually) invoke the super constructor which could be one of the 2 above.

If it helps, another example is if you inherits from UIViewController and then you create your own init you can only invoke one the two:

  1. init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?)
  2. init?(coder: NSCoder)

i.e:

init() {
  super.init(nibName: nil, bundle: nil)
}
OhadM
  • 4,687
  • 1
  • 47
  • 57
Tomas Camin
  • 9,996
  • 2
  • 43
  • 62