user5463574
user5463574

Reputation:

iOS / swift - constants in UIViewController in swift

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

Answers (2)

Sulthan
Sulthan

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

Tal Cohen
Tal Cohen

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

Related Questions