Doug Smith Doug Smith - 1 year ago 136
Swift Question

How do I make a custom initializer for a UIViewController subclass in Swift?

Apologies if this has been asked before, I've searched around a lot and many answers are from earlier Swift betas when things were different. I can't seem to find a definitive answer.

I want to subclass

and have a custom initializer to allow me to set it up in code easily. I'm having trouble doing this in Swift.

I want an
function that I can use to pass a specific
I'll then use with the view controller. In my mind it looks something like
init(withImageURL: NSURL)
. If I add that function it then asks me to add the
init(coder: NSCoder)

I believe this is because it's marked in the superclass with the
keyword? So I have to do it in the subclass? I add it:

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

Now what? Is my special initializer considered a
one? A designated one? Do I call a super initializer? An initializer from the same class?

How do I add my special initializer onto a

Answer Source
class ViewController: UIViewController {

    var imageURL: NSURL?

    // this is a convenient way to create this view controller without a imageURL
    convenience init() {
        self.init(imageURL: nil)

    init(imageURL: NSURL?) {
        self.imageURL = imageURL
        super.init(nibName: nil, bundle: nil)

    // if this view controller is loaded from a storyboard, imageURL will be nil

    /* Xcode 6
    required init(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)

    // Xcode 7 & 8
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download