You are viewing a free preview of this lesson.
Subscribe to unlock all 10 lessons in this course and every other course on LearningBro.
This lesson covers two essential topics: how Swift handles errors safely using throw/catch, and how Swift's structured concurrency model enables safe asynchronous and parallel code with async/await and actors.
Errors in Swift conform to the Error protocol. Enums are the most common way to define error types:
enum NetworkError: Error {
case badURL
case requestFailed(statusCode: Int)
case decodingFailed
case noData
}
enum ValidationError: Error {
case tooShort(minimum: Int)
case tooLong(maximum: Int)
case invalidFormat(String)
}
Functions that can fail are marked with throws:
func fetchUser(id: Int) throws -> User {
guard id > 0 else {
throw ValidationError.invalidFormat("ID must be positive")
}
guard let data = loadData(for: id) else {
throw NetworkError.noData
}
return try decode(data)
}
Use do-catch to handle thrown errors:
do {
let user = try fetchUser(id: 42)
print("Found user: \(user.name)")
} catch NetworkError.noData {
print("No data available")
} catch NetworkError.requestFailed(let statusCode) {
print("Request failed with status \(statusCode)")
} catch {
print("Unexpected error: \(error)")
}
Subscribe to continue reading
Get full access to this lesson and all 10 lessons in this course.