How to subclass a UIViewController and add properties in swift?

Max*_*Max 1 initialization properties uiviewcontroller ios 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")
  }
}
Run Code Online (Sandbox Code Playgroud)

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)
}
Run Code Online (Sandbox Code Playgroud)

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
Run Code Online (Sandbox Code Playgroud)

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?

pic*_*ano 5

在某些时候,视图控制器必须通过调用init(nibName:bundle:)init(coder:)

尝试这个:

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")
    }

}
Run Code Online (Sandbox Code Playgroud)