The problem typed throws solves
Before Swift 6, every throwing function threw any Error. A caller who wanted to handle specific failures had to cast in catch clauses and add a fallback for errors that could never happen. Result<Success, Failure> had a concrete error type, but converting between Result and throws lost it. SE-0413, implemented in Swift 6.0, lets a function name the one error type it throws, and lets the compiler check that catch handles every case.
That sounds like something you would want everywhere. The proposal itself says otherwise, and most of this article is about the difference.
How typed throws work
Declaring and catching
import Foundation
enum ValidationError: Error, Equatable {
case empty
case tooLong(limit: Int)
case invalidCharacters
}
func validateUsername(_ name: String) throws(ValidationError) -> String {
let trimmed = name.trimmingCharacters(in: .whitespaces)
guard !trimmed.isEmpty else { throw .empty }
guard trimmed.count <= 20 else { throw .tooLong(limit: 20) }
guard trimmed.allSatisfy({ $0.isLetter || $0.isNumber || $0 == "_" }) else {
throw .invalidCharacters
}
return trimmed
}
Inside the function, throw .empty works because the compiler knows the error type. At the call site, error in the catch block has the concrete type, so a switch over it is checked for exhaustiveness:
func message(for name: String) -> String {
do {
let valid = try validateUsername(name)
return "Hi, \(valid)"
} catch {
switch error {
case .empty: return "Enter a username."
case .tooLong(let limit): return "Use \(limit) characters or fewer."
case .invalidCharacters: return "Use letters, numbers and underscores."
}
}
}
No default case and no cast. Add a case to ValidationError and every switch like this one becomes a compile error until you handle it. Antoine van der Lee’s typed throws walkthrough makes this the headline benefit.
The do block’s error type
A do block infers its error type from what it calls. When everything inside throws the same type, catch gets that type. When it mixes types, you get any Error again. You can pin the type with do throws(...), and the compiler then rejects any call inside that throws something else:
func problems(in names: [String]) -> [ValidationError] {
var found: [ValidationError] = []
for name in names {
do throws(ValidationError) {
_ = try validateUsername(name)
} catch {
found.append(error)
}
}
return found
}
A do throws(...) block needs at least one catch. The compiler rejects one without.
throws(Never) and throws(any Error)
Typed throws generalize both ends. throws(any Error) is exactly the same as plain throws, and throws(Never) is exactly the same as not throwing. That is what makes the feature useful in generic code.
Replacing rethrows in generic code
A generic function can take the error type of a closure as a parameter and pass it through:
func transform<T, E: Error>(_ values: [T], _ body: (T) throws(E) -> T) throws(E) -> [T] {
var out: [T] = []
for value in values {
out.append(try body(value))
}
return out
}
Called with a non-throwing closure, E is Never and the call needs no try. Called with a closure that throws ValidationError, the call throws ValidationError. The standard library uses the same pattern in Result.init(catching:), Result.get() and the Task initializers.
Closures need an annotation
Here is the catch that trips people up. The compiler infers whether a closure throws from its body, but not what it throws. As Sarun Wongpatcharapakorn explains in Typed throws in Swift 6, a throwing closure without an annotation is inferred to throw any Error, even when every call inside throws one concrete type. Spell it out when you want to keep the type:
let validated = try? transform(["a"]) { (name: String) throws(ValidationError) -> String in
try validateUsername(name)
}
let result = Result { () throws(ValidationError) -> String in
try validateUsername("swift_dev")
}
result is a Result<String, ValidationError>. Without the annotation it would be Result<String, any Error>. SE-0413 lists closure thrown-type inference as a future direction, so this may get easier, but today it is required.
When to use them, and when not
SE-0413 includes a section titled “When to use typed throws” that is unusually direct. It says untyped throws is better for most scenarios, because errors are usually propagated or rendered, not exhaustively handled. It names three cases where typed throws fit:
- Code inside a module or package where you always handle the error, so the error type is an implementation detail.
- Generic code that only passes errors through, like
transformabove. - Dependency-free code for constrained environments such as Embedded Swift, where avoiding an existential
any Errorbox matters.
It also warns against the obvious temptation: using typed throws because an implementation happens to throw only one kind of error today. Once a public function promises throws(FileError), it cannot later start loading from the network without either translating every network error into FileError or breaking its contract.
The community largely agrees with the proposal. Sarun recommends keeping public APIs untyped for the same evolution reason. Antoine van der Lee is more enthusiastic, and argues that SDKs in particular benefit because callers can predict exactly which errors to expect. Those two views meet in the middle: a typed error works well for an SDK that owns its failure domain completely, such as a validator or a parser, and badly for one that wraps the network, the file system or another library.
This article recommends: plain throws by default; typed throws for validation and parsing logic whose error enum is complete, for internal helpers whose callers always switch over the result, and for generic pass-through code. Never on a public API that touches I/O.
Where Result still fits
With typed throws, throws can express everything Result can, and Swift code reads better with try than with chains of map and flatMap. Result is still the right tool when you need to store an outcome: in a property, a collection, a cache, or a message sent between parts of the app.
Converting is direct. Result(catching:) keeps the closure’s error type when the closure is annotated, and get() throws the Failure type back. Swift 6.4 adds an async overload (SE-0530), so await Result { try await load() } works without a helper. It needs the Swift 6.4 compiler, but the SDK inlines it into your app, so it is not tied to a new OS version.
Designing errors for an app
Typed throws are a tool for the inner layers. What matters more for an app is the shape of the errors that reach the UI.
Translate at the boundary
Low-level errors (URLError, DecodingError, CKError, CocoaError) carry detail that is useful in logs and meaningless to users. Pick a boundary per feature, usually the service a view model calls, and translate there into a small enum that describes what the user can do something about:
import Foundation
enum SyncError: LocalizedError {
case offline
case quotaExceeded
case server(status: Int)
var errorDescription: String? {
switch self {
case .offline: String(localized: "You're offline.")
case .quotaExceeded: String(localized: "iCloud storage is full.")
case .server: String(localized: "The server couldn't finish the sync.")
}
}
var recoverySuggestion: String? {
switch self {
case .offline: String(localized: "Your changes will sync when you're back online.")
case .quotaExceeded: String(localized: "Free up space in Settings, then try again.")
case .server: String(localized: "Try again in a moment.")
}
}
}
struct Note: Sendable { let id: UUID }
protocol NoteSyncing: Sendable {
func push(_ notes: [Note]) async throws
}
func sync(_ notes: [Note], with client: some NoteSyncing) async throws(SyncError) {
do {
try await client.push(notes)
} catch let error as URLError where error.code == .notConnectedToInternet {
throw .offline
} catch let error as SyncError {
throw error
} catch {
throw .server(status: 0)
}
}
This is a good use of typed throws by the proposal’s own rules: sync is internal to the app, the view model always handles the result, and SyncError is complete by design because the last catch maps everything else to .server. The client underneath stays untyped, because it can fail in ways nobody has listed yet.
Log the original error before you translate it. The user sees “The server couldn’t finish the sync”. You need the status code and the underlying error.
Show it
SwiftUI’s alert(isPresented:error:actions:message:), available from iOS 15, takes any LocalizedError and uses its errorDescription as the title:
import SwiftUI
struct DummyClient: NoteSyncing {
func push(_ notes: [Note]) async throws {}
}
@MainActor
@Observable
final class SyncModel {
var lastError: SyncError?
var isShowingError = false
func syncNow(_ notes: [Note]) async {
do {
try await sync(notes, with: DummyClient())
} catch {
lastError = error
isShowingError = true
}
}
}
struct SyncButton: View {
@State private var model = SyncModel()
var body: some View {
Button("Sync now") {
Task { await model.syncNow([]) }
}
.alert(isPresented: $model.isShowingError, error: model.lastError) { _ in
Button("OK") {}
} message: { error in
Text(error.recoverySuggestion ?? "")
}
}
}
Because sync throws SyncError, error in syncNow’s catch is already a SyncError. No cast and no fallback message.
Not every error deserves an alert. Use an alert when the user must decide something or lost work. Use inline text near the field for validation, a banner or a status row for background sync, and nothing at all for cancellation.
Traps and edge cases
- CancellationError is not a failure. When a task is cancelled,
URLSessionandTask.sleepthrowCancellationError. Do not show it. Catch it first and return quietly, or map it to a case your UI ignores. - Silent errors in tasks.
Task { try await save() }swallows the error. Swift 6.4 (SE-0520) adds a warning when a throwing task is never used. Handle the error inside the task. - try? hides real failures.
try?is fine for “best effort” work like prefetching. For loading the user’s data, it turns a broken file into an empty screen with no explanation. - Typed errors leak implementation. A
publicerror enum that mirrors a database library’s cases ties your API to that library. Model what the caller can act on. - Async cleanup. Swift 6.4 lets
defercontainawait(SE-0493), so cleanup such as closing a connection runs on both the return and the throw path without duplicating it in eachcatch. - Localize the strings.
errorDescriptionis user-facing text. UseString(localized:)so it lands in your String Catalog.
Decision table
| Situation | Use |
|---|---|
| Public API, may fail in new ways later | throws |
| Validation or parsing with a complete error enum | throws(MyError) |
| Internal service whose callers always switch over errors | throws(FeatureError) |
| Generic function that runs a caller’s closure | throws(E) with E generic |
| Storing an outcome for later | Result<Success, Failure> |
| Error shown to the user | A LocalizedError enum mapped at the feature boundary |
| Task was cancelled | Return quietly, show nothing |
Sources and further reading
- SE-0413: Typed throws Swift Evolution
- SE-0530: Async Result Support Swift Evolution
- Typed throws in Swift explained with code examples Antoine van der Lee, SwiftLee
- Typed throws in Swift 6 Sarun Wongpatcharapakorn, Sarunw
- alert(isPresented:error:actions:message:) Apple Developer Documentation
- SE-0520: Discardable result use in Task initializers Swift Evolution
- Swift 6.4 Released swift.org