Jason
Jason

Reputation: 1067

init(coder:) has not been implemented in swift

I have this class file for accepting card payments

import UIKit
class PaymentViewController: UIViewController , PTKViewDelegate {

    var card : STPCard
    var PaymentView : PTKView
    var button   = UIButton.buttonWithType(UIButtonType.System) as UIButton

    init(PaymentView : PTKView , button : UIButton, card : STPCard) {
        self.PaymentView = PaymentView
        self.button = button
        self.card = card
        super.init()
    }
    required init(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
}

When I build it, it works fine, but when I execute it (run it) on my actual device , I get

fatal error: init(coder:) has not been implemented.

Any ideas ?

Upvotes: 21

Views: 29291

Answers (2)

JMFR
JMFR

Reputation: 809

Based on the Inheritance Hierarchy you have setup. PaymentViewController will inherit 3 init methods. UIViewController provides init(nibName:bundle) as its designated initializer. UIViewController also conforms to NSCoding which is where the required init(coder:) comes from. UIViewController also inherits from NSObject which provides a basic init() method.

UIViewController inherited init methods diagram

The problem you are having stems from init(coder: being called when the ViewController is instantiated from a .xib or storyboard. This method is called to un-archive the .xib/storyboard objects.

From the Documentation:

iOS initializes the new view controller by calling its initWithCoder: method instead.

You should be calling the superclass designated initializer in your init method, which is init(nibName:bundle) Note: it is fine for both of those parameters to be nil. Also your init(coder:) override should call super.init(coder:)

Upvotes: 20

Bright
Bright

Reputation: 5741

A simple workaround will do:

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

Upvotes: 11

Related Questions