I have a ViewController
, which need to be initialized with ViewModel: NSObject
.
My implementation of ViewController
is:
class ViewController: UIViewController {
let viewModel: ViewModel
init(withViewModel viewModel: ViewModel) {
self.viewModel = viewModel
super.init(nibName: nil, bundle: nil)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
ViewModel
has simple override init
:
class ViewModel: NSObject {
override init() {
super.init()
// Some other logic
}
}
I understand, that I need required init?(coder aDecoder: NSCoder)
in ViewController
implementation since it conforms NSCoding
protocol. But I'm not sure if it is safe to have fatalError
there.
When I change fatalError
to super.init(coder: aDecoder)
I receive
property 'self.viewModel' not initialized at super.init call
I don't want to make viewModel
an optional variable, because in my App logic it can't be nil
.
Also, when I change init?(coder...
to
required init?(coder aDecoder: NSCoder) {
self.viewModel = ViewModel()
super.init(coder: aDecoder)
}
this also doesn't satisfy me, since viewModel
isn't the only constant, which need to be implemented during initialization of ViewController
.
So, my questions:
fatalError
in this init
method?init?(coder...
method won't run in any case?fatalError
?Thanks for any help!
Since you don't use storyboard you can disable your init, so you won't be able to use it in code:
@available(*, unavailable) required init?(coder aDecoder: NSCoder) {
fatalError("disabled init")
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With