Quick Answer

try, catch, and error propagation

Understanding the Issue

Swift provides multiple error handling approaches: throwing functions, Result types, and optional try? for when you don't need error details.

The Problem

This code demonstrates the issue:

Swift Error
// Problem: No error handling
let data = try parse(json: invalidJson) // Crash

The Solution

Here's the corrected code:

Swift Fixed
// Solution: Multiple approaches
// 1. do-try-catch
do {
    let data = try parse(json: validJson)
} catch {
    print(error)
}

// 2. Optional try
if let data = try? parse(json: json) {
    // success
}

// 3. Result type
func parse(json: String) -> Result<Data, Error>

Key Takeaways

Choose error handling approach based on how callers should handle failures.