SwiftUI provides a variety of ways to handle errors effectively while building user interfaces. Here are some common error handling patterns in SwiftUI:
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"])
}
}
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"])))
}
}
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()
}
}
}
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?