What are error handling patterns for SwiftUI in Swift?

SwiftUI provides a variety of ways to handle errors effectively while building user interfaces. Here are some common error handling patterns in SwiftUI:

Using Try-Catch in ViewModels

Encapsulate your state management and error handling within a ViewModel using Swift's traditional try-catch mechanism:

class MyViewModel: ObservableObject { @Published var data: String = "" @Published var errorMessage: String? func fetchData() { do { // Example function that can throw an error data = try loadData() } catch { errorMessage = "Failed to load data: \(error.localizedDescription)" } } func loadData() throws -> String { // Simulate a possible error throw NSError(domain: "", code: 1, userInfo: [NSLocalizedDescriptionKey: "Data not found"]) } }

Using Result Type

Another pattern is to use the Result type to encapsulate success or failure in your async operations:

class MyViewModel: ObservableObject { @Published var result: Result? func fetchData() { fetchDataAsync { result in DispatchQueue.main.async { self.result = result } } } func fetchDataAsync(completion: @escaping (Result) -> Void) { // Simulate an async fetch operation completion(.failure(NSError(domain: "", code: 1, userInfo: [NSLocalizedDescriptionKey: "Data not found"]))) } }

Displaying Errors in the View

In your SwiftUI view, you can conditionally show error messages based on your ViewModel's state:

struct ContentView: View { @StateObject var viewModel = MyViewModel() var body: some View { VStack { if let errorMessage = viewModel.errorMessage { Text(errorMessage) .foregroundColor(.red) } else { Text(viewModel.data) } } .onAppear { viewModel.fetchData() } } }

SwiftUI error handling Swift ViewModel try-catch Result type