Quick Answer
Throwing, propagating, and catching errors in Swift
Understanding the Issue
Swift errors are represented by types conforming to the Error protocol. Functions can throw errors, and callers must handle them with do-try-catch or propagation.
The Problem
This code demonstrates the issue:
Swift
Error
// Problem: No error handling
let data = try parse(json: invalidJson) // Compiler error
The Solution
Here's the corrected code:
Swift
Fixed
// Solution: do-try-catch block
do {
let data = try parse(json: jsonString)
print(data)
} catch ParsingError.invalidFormat {
print("Invalid JSON format")
} catch {
print("Other error: (error)")
}
// Alternative: try? for optional result
if let data = try? parse(json: jsonString) {
// handle data
}
Key Takeaways
Use do-try-catch for comprehensive error handling or try? when errors can be safely ignored.