What are recommended project structure for Combine in Swift?

When working with Combine in Swift, it's essential to have a well-structured project to maintain code clarity and ease of use. Here are some recommended project structures that you can follow when integrating Combine into your Swift projects:

Recommended Project Structure

  • Models: This directory contains data models that represent the data structure used in your app.
  • Views: All UI components and view files go into this directory, making it easy to manage the user interface.
  • ViewModels: Here you will implement your Combine publishers and subscribers, acting as the bridge between Models and Views.
  • Services: Place your networking and data-fetching logic here. This is where you can handle HTTP requests and responses using Combine.
  • Extensions: Any Swift extensions or utility functions can be stored here for better code organization.
  • Resources: Store assets such as images, localization files, or any other resources needed by your app.
  • Supporting Files: This includes the app configuration files such as Info.plist and any other necessary setup files.

Example of a ViewModel using Combine

import Foundation import Combine class MyViewModel: ObservableObject { @Published var data: [String] = [] private var cancellables = Set() private let dataService: DataService init(dataService: DataService) { self.dataService = dataService // Subscribe to data updates dataService.$data .sink { [weak self] updatedData in self?.data = updatedData } .store(in: &cancellables) } }

Combine Swift Project Structure ViewModel Reactive Programming