Reputation:
Suppose I have a view model that my controller uses for asking some data or functionality, that view model will Never changes when I instantiated once, right? but in view controllers I navigate with perform segue and so on, I have no access to initializer then I can't use some thing like this:
let myViewModel: MyViewModel
then I have to use this instead:
var myViewModel: MyViewModel!
and I have no good feeling about this, can anyone suggest a good solution? tnx mates :)
Upvotes: 1
Views: 300
Reputation: 130200
When view controllers are loaded from storyboard, you have no control over initialization (since the controller is not initialized by you), therefore there is nothing else you can do. The other options are similar and there is no real advantage to either of them. It's a subjective decision:
You could declare the variable as a normal optional
var myViewModel: MyViewModel?
but if the controller really cannot work without data being set, I prefer to use !
myself because not setting the data model should be a fatal error.
In some cases you can also go with a default value, e.g.:
var myViewModel = MyViewModel()
My data setters usually look like this:
var model: Model! {
didSet {
loadViewIfNeeded() // to force view be loaded and viewDidLoad called
updateUI() // set UI values from the data model
}
}
Upvotes: 1
Reputation: 1457
That's totally fine, same for your IBOutlets.
From the moment you instantiate the ViewController until you set up the model, it's value is nil
. that means it's not a constant even though you don't change it through the lifecycle of the ViewController.
Upvotes: 1