Checkout process example
SwiftUI approach
// Model layer
class Checkout: ObservableObject { ... }
// View layer
struct CheckoutView: View {
@StateObject private var checkout = Checkout()
var body: some View {
NavigationStack {
CheckoutProductInfoForm()
// -> CheckoutOffersView()
// -> CheckoutBuyerForm()
// -> CheckoutDeliveryInfoForm()
// -> CheckoutSummaryView()
}
.environmentObject(checkout)
}
}
Advantages:
Clean, simple and data-driven development
Core for declarative UI platforms
Checkout model object is independent from a specific View and platform
Works great for multiplatform (inside Apple ecosystem)
Disadvantages:
Other platform devs don’t (yet) understand it
MVVM approach
// Need a model or helper object to share / joint data between the VMs
// ViewModel layer
class CheckoutProductInfoViewModel: ObservableObject { ... }
class CheckoutOffersViewModel: ObservableObject { ... }
class CheckoutBuyerViewModel: ObservableObject { ... }
class CheckoutDeliveryInfoViewModel: ObservableObject { ... }
class CheckoutSummaryViewModel: ObservableObject { ... }
// View layer
struct CheckoutView: View {
var body: some View {
NavigationStack {
CheckoutProductInfoView() // <- CheckoutProductInfoViewModel
// -> CheckoutOffersView() <- CheckoutOffersViewModel
// -> CheckoutBuyerView() <- CheckoutBuyerViewModel
// -> CheckoutDeliveryInfoView() <- CheckoutDeliveryInfoViewModel
// -> CheckoutSummaryView() <- CheckoutSummaryViewModel
}
}
}
Advantages:
Sometimes we feel that using VMs can help to avoid massive views (but not really necessary -> SwiftUI component nature)
Disadvantages:
A middle layer, unnecessary, more objects / files, more code, more complexity
Not easy to handle some use cases, becomes problematic in some situations
Not easy to share a state in view hierarchy
ViewModel-View dependence becomes bad for multiplatform (iOS UI != iPad UI != TV UI …)
Old approach, not suitable for declarative platforms
Can fight the SwiftUI platform
Topic:
UI Frameworks
SubTopic:
SwiftUI
Tags: