Search code examples
iosswiftmodel-view-controllerviewmodel

What are the benefits of creating a configure method to pass in view model versus passing in view model through the init of a View?


I have seen both patterns where you have a view model for a view and you can either pass the view model in through the init of the view or have a configure method that takes in the view model and configures the property. What are the pros and cons for those patterns?

i.e.

struct ViewModel {
    let titleLabel: String
    let subtitleLabel: String
}

init method:

class View: UIView {
    let viewModel: ViewModel
    init(viewModel: viewModel) {
        self.viewModel = viewModel
    }
}

configure method:

class View: UIView {
    init() {}
    
    configure(viewModel: ViewModel) {
        // configuring view properties
    }
}

Solution

  • Generally, if you can set properties of an object during from its initializer, it's preferable to do so, because you won't need the properties to be optional (or worse, have non-sense default values like 0 for ints, false for bools, etc.).

    You also get the benefit of Swift's definite-initialization guarantees, which ensure that you can't forget to set any properties from the initializer. Contrast this with the configure(viewModel:) method, which you can forget to call.

    However, there are times when this simply isn't possible, such as when using Storyboards (which initialize the views for you, without a chance for you to pass through any arguments to the initializer) or when you're building views that are meant to be recycled (such as cells in a table view).