简体   繁体   中英

How to subclass a UIViewController and add properties in swift?

I want to make a new kind of view controller in Swift that has an additional property that must be explicitly initialized. It doesn't make any sense for this property to be nil or have a default value and the controller will only be initialized programmatically. I tried defining it like this:

class MyController : UIViewController {
  var prop: Int
  init(prop: Int) {
    self.prop = prop
    super.init()
  }

  required init(coder aDecoder: NSCoder?) {
    fatalError("don't serialize this")
  }
}

I tried running this but it crashed because super.init() tries to run the nib constructor which isn't defined, so I tried adding that:

override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) {
  super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
}

But now the compiler complains that prop isn't being initialized. And this is my question: how can I initialize prop correctly here? I don't want a default value, and anything I set will override the correct value that I set in the other initializer.

I kinda hacked around it by setting some default value in the nib init, but then having my first init do this

self.prop = prop
super.init()
self.prop = prop

But other than being really weird and ugly, that makes me worried that now it is possible to initialize my view controller from a nib and end up with the default value, which would be bad.

What is the correct and idiomatic way to do this in Swift?

At some point the view controller must be initialized by calling init(nibName:bundle:) or init(coder:)

Try this:

class MyViewController: UIViewController {

    var prop: Int

    init(prop: Int, nibName nibNameOrNil: String? = nil, bundle nibBundleOrNil: Bundle? = nil) {
        self.prop = prop
        super.init(nibName:nibNameOrNil, bundle: nibBundleOrNil)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

}

Try the following

class MyController: UIViewController {

    var prop: Int

    required init?(coder aDecoder: NSCoder) {
        fatalError()
    }

    init(prop: Int) {
        self.prop = prop
        super.init(nibName: nil, bundle: nil)
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM