nalexn / clean-architecture-swiftui

SwiftUI sample app using Clean Architecture. Examples of working with CoreData persistence, networking, dependency injection, unit testing, and more.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Decoupling Model from View

ashrobo opened this issue · comments

commented

Hey, thanks for sharing your project.

One thing I’ve noticed in many examples including Apples and your own is that, although we’re abstracting a lot from the view via the view model, the view still has direct knowledge of the model. For example List(viewModel.countries), Country is a model object and now the view knows about it and will directly access its properties (i.e Text(country.name). Is this acceptable in SwiftUI?

In UIKit, the view controller would know about the Country object but would configure the Cell (view) with just the String representing country.name (normally we wouldn’t pass the model to the view directly so that view can be reused elsewhere if required). But in SwiftUI the the thing configuring the list is also a view.

Interested to know your thoughts on that, as we effectively treating our top level views as controllers?

Hey @AshRobinson

My apologies for the late response!

Is this acceptable in SwiftUI?

There is rarely something unacceptable in the software, there are best practices for sure (and bad once too), but I would never take either one too serious :)

SwiftUI is all about speeding up the development. You can see Apple promoting things like @FetchRequest where database details get exposed to the UI. Some seasoned devs would say this is absolutely unacceptable, but there are apps (especially small ones) that benefit from this simplification.

The view has to operate with data (display it), one way or another it would need to read it from somewhere. You can feed it with a data source hidden behind a protocol that returns a formatted string instead of reading it from the data model like so Text(country.name), but the question "is it worth it" remains open. In some cases - yes, if the data model structure is changing often, or the data has to be processed or formatted in a non-trivial way, or the way you retrieve data from the view model is somewhat complicated (long path to the value, complex async API), then hiding the access behind a facade is a good idea. But I would refrain from doing so for every case without such consideration.