How to answer
I start from an isolation map: every type in the layer is either immutable and Sendable, an actor, or @MainActor, and nothing else crosses a boundary. The client is a struct holding only Sendable configuration (a URLSession behind a Sendable transport protocol, a base URL), so it can be called from anywhere. Mutable shared state, such as the token cache, single-flight refresh and in-flight request deduplication, lives in actors. Request and response types are Sendable value types, and view models are @MainActor @Observable classes that await the layer from .task. Finally, I make sure decoding doesn't happen on the main actor: with Swift 6.2's approachable concurrency a nonisolated async method runs on the caller's actor, so the client's entry point is @concurrent.
Key points
- Client:
struct APIClient: Sendablewithletproperties only; injectany HTTPTransport(aSendableprotocol) for tests - DTOs:
struct … : Decodable, Sendable; generic methods constrainT: Decodable & Sendableso results can cross back to the caller's actor - Actors for state:
TokenProviderholdingTask<Token, any Error>?, a loader holding[Key: Task<Value, any Error>]to share in-flight requests Mutex(Synchronization) for state touched from synchronous callbacks, likeURLSessionDelegatemethods, where you can'tawaitan actor: a delegate can be afinal class …: NSObject, URLSessionTaskDelegate, Sendablewhose only stored property is aletMutex@concurrenton CPU-heavy entry points (decoding large payloads) so a@MainActorcaller doesn't decode on main- Cancellation is free: SwiftUI
.taskcancels theTask, URLSession cancels the request, andCancellationError/URLError(.cancelled)should not show an error UI
If they dig deeper
Default MainActor isolation (new Xcode 26+ app targets): in that mode every unannotated type, including its protocol conformances, is @MainActor, so a DTO's Decodable conformance becomes main-actor-isolated and can't satisfy a generic T: Decodable & Sendable requirement. Put the networking layer in an SPM package (packages don't default to MainActor) or mark DTOs and the client nonisolated. Actor reentrancy: between awaits an actor's state can change, which is why you store the in-flight Task rather than a Boolean flag. sending parameters and region isolation let you pass a freshly built non-Sendable value (e.g. a URLRequest builder) into an actor once. Wrapping old completion-handler APIs with withCheckedThrowingContinuation, resuming exactly once.
Common pitfalls
final class APIClient with var token and @unchecked Sendable to silence errors. A singleton static var shared (an error in Swift 6 unless isolated or immutable). Assuming async means "off the main thread" and decoding 5 MB of JSON on main. Making the whole layer @MainActor to make errors go away. Hopping to MainActor.run inside the client instead of returning Sendable values. Putting Task.detached everywhere.
How to use it
The client: immutable, Sendable, and explicit about where work runs.
import Foundation
protocol HTTPTransport: Sendable {
func data(for request: URLRequest) async throws -> (Data, URLResponse)
}
extension URLSession: HTTPTransport {
func data(for request: URLRequest) async throws -> (Data, URLResponse) {
try await data(for: request, delegate: nil)
}
}
protocol TokenSource: Sendable { // implemented by an actor with single-flight refresh
func accessToken() async throws -> String
}
enum APIError: Error { case status(Int), notHTTP }
struct APIClient: Sendable { // only immutable Sendable state
let baseURL: URL
let transport: any HTTPTransport
let tokens: any TokenSource
/// @concurrent: runs off the caller's actor, so a @MainActor caller doesn't decode on main.
@concurrent
func get<T: Decodable & Sendable>(_ path: String, as: T.Type = T.self) async throws -> T {
var request = URLRequest(url: baseURL.appending(path: path))
request.setValue("Bearer \(try await tokens.accessToken())", forHTTPHeaderField: "Authorization")
let (data, response) = try await transport.data(for: request)
guard let http = response as? HTTPURLResponse else { throw APIError.notHTTP }
guard (200..<300).contains(http.statusCode) else { throw APIError.status(http.statusCode) }
return try JSONDecoder().decode(T.self, from: data)
}
}Shared state in an actor, UI state on the main actor:
import Observation
nonisolated struct Profile: Decodable, Sendable { // nonisolated: needed under default MainActor isolation
let id: Int
let name: String
}
actor ProfileLoader {
private let client: APIClient
private var inFlight: [Int: Task<Profile, any Error>] = [:]
init(client: APIClient) { self.client = client }
func profile(id: Int) async throws -> Profile {
if let existing = inFlight[id] { return try await existing.value } // join, don't duplicate
let client = self.client
let task = Task { try await client.get("/v1/profiles/\(id)", as: Profile.self) }
inFlight[id] = task
defer { inFlight[id] = nil }
return try await task.value
}
}
@MainActor
@Observable
final class ProfileModel {
private(set) var profile: Profile?
private(set) var errorMessage: String?
private let loader: ProfileLoader
init(loader: ProfileLoader) { self.loader = loader }
func load(id: Int) async { // call from .task: cancellation flows down
do { profile = try await loader.profile(id: id) }
catch is CancellationError { }
catch { errorMessage = error.localizedDescription }
}
}Best practices
- Classify every type as
Sendablevalue, actor, or@MainActorbefore writing code - Keep the client a
Sendablestruct; push mutable state into actors (or aMutexfor synchronous callbacks) - Mark heavy entry points
@concurrent; don't rely onasyncto leave the main actor - Ship the layer as an SPM package, or mark DTOs
nonisolated, when the app target defaults to MainActor - Avoid
@unchecked Sendableandnonisolated(unsafe)unless you can explain the invariant
Related concepts
- REST API client design, request interceptors, authentication (single-flight refresh), request deduplication, mock networking, actors and reentrancy,
@concurrent/ approachable concurrency,Mutex