// MARK: - Dependencies Protocol
protocol HasAuthService {
var authService: AuthServiceProtocol { get }
}
protocol HasProductRepository {
var productRepository: ProductRepositoryProtocol { get }
}
typealias AppDependencies = HasAuthService & HasProductRepository
// MARK: - DI Container
final class DependencyContainer: AppDependencies {
// Singletons
lazy var authService: AuthServiceProtocol = AuthService()
// Factories
lazy var productRepository: ProductRepositoryProtocol = {
ProductRepository(
remoteDataSource: ProductRemoteDataSource(apiClient: apiClient),
localDataSource: ProductLocalDataSource(database: database)
)
}()
private lazy var apiClient: APIClientProtocol = APIClient()
private lazy var database: DatabaseProtocol = Database()
// Factory methods for ViewModels
func makeProductListViewModel(coordinator: ProductCoordinator) -> ProductListViewModel {
ProductListViewModel(
getProductsUseCase: GetProductsUseCase(repository: productRepository),
coordinator: coordinator
)
}
}
// MARK: - Property Wrapper Approach
@propertyWrapper
struct Injected<T> {
private let keyPath: KeyPath<DependencyContainer, T>
var wrappedValue: T {
DependencyContainer.shared[keyPath: keyPath]
}
init(_ keyPath: KeyPath<DependencyContainer, T>) {
self.keyPath = keyPath
}
}
// Usage
final class SomeService {
@Injected(\.authService) private var authService
}
SwiftUI MVVM
// MARK: - View
struct ProductListView: View {
@StateObject private var viewModel: ProductListViewModel
init(viewModel: @autoclosure @escaping () -> ProductListViewModel) {
_viewModel = StateObject(wrappedValue: viewModel())
}
var body: some View {
Group {
if viewModel.isLoading {
ProgressView()
} else if let error = viewModel.error {
ErrorView(error: error) {
Task { await viewModel.loadProducts() }
}
} else {
productList
}
}
.navigationTitle("Products")
.task {
await viewModel.loadProducts()
}
}
private var productList: some View {
List(viewModel.products) { product in
ProductRow(product: product)
.onTapGesture {
viewModel.selectProduct(product)
}
}
}
}
// MARK: - SwiftUI Coordinator (Router)
@MainActor
final class Router: ObservableObject {
@Published var path = NavigationPath()
func push<T: Hashable>(_ value: T) {
path.append(value)
}
func pop() {
path.removeLast()
}
func popToRoot() {
path.removeLast(path.count)
}
}
struct ContentView: View {
@StateObject private var router = Router()
@StateObject private var dependencies = DependencyContainer()
var body: some View {
NavigationStack(path: $router.path) {
ProductListView(viewModel: dependencies.makeProductListViewModel(router: router))
.navigationDestination(for: Product.self) { product in
ProductDetailView(product: product)
}
}
.environmentObject(router)
}
}
Troubleshooting
Common Issues
Issue
Cause
Solution
Massive ViewModel
Too many responsibilities
Split into smaller VMs or use UseCases
Tight coupling
Direct dependencies
Use protocols and DI
Hard to test
Static/singleton dependencies
Inject dependencies
Memory leaks
Strong coordinator references
Use weak delegates
State sync issues
Multiple sources of truth
Single source + binding
Debug Tips
// Check retain cycles
deinit {
print("\(Self.self) deinit")
}
// Trace view updates
var body: some View {
let _ = Self._printChanges()
// ...
}
// Validate architecture
// Run: swift package diagnose-api-breaking-changes
Validation Rules
validation:
- rule: layer_separation
severity: error
check: Views should not import data layer
- rule: protocol_abstractions
severity: warning
check: Dependencies should be protocols
- rule: unidirectional_flow
severity: info
check: State changes flow in one direction