Error Handling in Swift
Swift provides several ways to handle errors, including throwing functions and the Result type.
Defining Errors
enum NetworkError: Error {
case invalidURL
case timeout
case serverError(status: Int)
}
Throwing Functions
func fetchData(from urlString: String) throws -> Data {
guard let url = URL(string: urlString) else {
throw NetworkError.invalidURL
}
// ... fetch data
}
Do-Try-Catch
do {
let data = try fetchData(from: "https://example.com")
print("Data received")
} catch NetworkError.invalidURL {
print("Invalid URL")
} catch {
print("Other error: \(error)")
}
Try? and Try!
let data1 = try? fetchData(from: "badurl") // nil on error
let data2 = try! fetchData(from: "goodurl") // Crash on error
Result Type
func fetchDataResult(from url: String) -> Result<Data, NetworkError> {
guard URL(string: url) != nil else {
return .failure(.invalidURL)
}
// ... return .success(data)
}
switch fetchDataResult(from: "https://example.com") {
case .success(let data):
print("Data: \(data)")
case .failure(let error):
print("Error: \(error)")
}
Assertions
let age = -3
assert(age >= 0, "Age can't be negative") // Debug builds only
precondition(age >= 0, "Age can't be negative") // All builds
← Back to Tutorials