Group Group Group Group Group Group Group Group Group

MVVM and SwiftUI

I’m still learning SwiftUI but I’m wondering if navigation and dependency injection are still done more or less the same way as is shown in the book or if it’s completely different?

hi @mfilipowicz, in SwiftUI navigation is done similarly to the book. It’s not the exact same way, but similar in that both the book and SwiftUI navigation is driven off of value type models.

Dependency injection on the other hand is very different. For dependency injection, the official approach from Apple is to use @EnvironmentObject for reference type dependencies and @Environment for value type dependencies. Just a word of caution, be careful when using @EnvironmentObject because SwiftUI will crash/trap if for some reason an object of the dependency’s type is not provided by a parent’s view .environmentObject modifier.

I’ve explored applying the dependency container approach from the book towards SwiftUI, and so far I’ve found it to be tricky because you can’t necessarily trust SwiftUI view structs to hold onto the dependency containers, since they are value types and view hierarchies in SwiftUI get recomputed often; so views get recreated all the time. I suggest starting with @EnvironmentObject to see how well it fits your needs and exploring the dependency container approach if you’d like something different than @EnvironmentObject.

If you’re looking for examples of MVVM with SwiftUI, we recently released a really great tutorial that’s worth checking out: https://www.raywenderlich.com/4161005-mvvm-with-combine-tutorial-for-ios

Please let me know if you have any follow on questions or if I can clarify anything. Hope this helps. Cheers!

thanks! Will the book be updated for SwiftUI?

@mfilipowicz we just released the second edition which has a new short chapter on advice on getting your app’s architecture ready for SwiftUI. We are definitely considering updating the book with SwiftUI content. Because SwiftUI is so new we would like to see what architecture patterns come out of teams using SwiftUI in real world projects. In the meantime, feel free to ask any questions here if you have any architectural questions while working with SwiftUI.