Load A Large JSON Feed Without Blocking Interaction
The network request finishes quickly, but the screen freezes before its rows appear. The response is already on the device. The expensive part is decoding it, validating identifiers, and building the values the list actually displays.
Putting all of that inside Task {} in a main-actor model does not automatically move the synchronous work away from the main actor.
Give processing an explicit owner
JSONDecoder.decode is synchronous. A dedicated actor can own that work and return sendable values to the UI model.
This example preserves server order, hides archived entries, and rejects duplicate identities rather than silently producing an ambiguous list:
import Foundation
struct FeedItem: Codable, Sendable, Equatable {
let id: Int
let title: String
let archived: Bool
}
struct FeedRow: Sendable, Equatable {
let id: Int
let title: String
}
actor FeedDecoder {
enum Failure: Error {
case tooLarge
case duplicateID(Int)
}
func rows(from data: Data) throws -> [FeedRow] {
try Task.checkCancellation()
guard data.count <= 8 * 1024 * 1024 else { throw Failure.tooLarge }
let items = try JSONDecoder().decode([FeedItem].self, from: data)
var seen: Set<Int> = []
var rows: [FeedRow] = []
rows.reserveCapacity(items.count)
for (index, item) in items.enumerated() {
if index.isMultiple(of: 64) { try Task.checkCancellation() }
guard seen.insert(item.id).inserted else { throw Failure.duplicateID(item.id) }
if !item.archived { rows.append(FeedRow(id: item.id, title: item.title)) }
}
try Task.checkCancellation()
return rows
}
}
An external caller uses try await decoder.rows(from: data). Keep the decoder as a dependency of the feature rather than constructing a new one for every row. The actor-isolated method has no suspension points, so its synchronous processing is serialized on that actor.
The returned rows are value types with explicit Sendable conformance. Do not move a main-actor view model, managed persistence object, or mutable formatter into the worker just because the compiler can be silenced with an unchecked conformance.
Publish once after validation
The actor builds a local array and returns it only after all checks succeed. The UI can replace its previous snapshot once. It does not append a row to published state on every loop iteration.
That reduces intermediate UI states and makes failure behavior easier to explain. If row 800 has a duplicate ID, the app can keep the last valid feed and show a refresh error instead of leaving a half-updated list on screen.
Partial success is a valid alternative for some products, but design it explicitly. A response containing accepted rows plus structured rejected-row diagnostics is different from catching every decode error and quietly dropping data.
Duplicate validation includes archived rows in this sample because the endpoint promises globally unique IDs within the response. If your API makes a different promise, encode that contract rather than borrowing this check blindly.
Bound the response before it becomes a problem
The eight-megabyte limit protects this decoder from unexpectedly large inputs. It does not undo the allocation of a Data value already received from the network, and it does not bound the expanded Swift object graph.
Enforce transport limits earlier where appropriate. More importantly, ask whether the screen should receive the entire collection at all. Pagination, incremental database updates, or a server response containing only the fields the UI needs can remove more work than relocating an enormous decode.
A single JSON array is still one decode operation here. Wrapping its Data in an AsyncSequence does not turn JSONDecoder into an incremental parser. If progressive results are a requirement, use an API contract and parser that actually support independently framed records.
Make cancellation and freshness separate checks
The loop checks cancellation periodically rather than for every tiny property assignment. The decoder call itself remains synchronous and is not interrupted by those checks. Once it returns, the next check can discard an unwanted result.
The main-actor owner also needs to confirm that the result belongs to its current refresh. An older request can complete after a newer request or account change. Our search-result article demonstrates the request-identity check that protects that publication decision.
Avoid scheduling a decode for every transient search keystroke when a newer request has already replaced it. Moving CPU work away from UI isolation improves responsiveness; it does not make unlimited obsolete work free.
Measure the whole refresh
Separate network completion, decoding, projection, publication, and the first useful frame in a trace. A fast worker can still hand the main actor thousands of rows that are expensive to lay out or observe.
Use representative payloads, including long titles, empty feeds, malformed fields, and duplicate IDs. Keep correctness assertions beside performance experiments so a faster path cannot succeed by dropping required data.
September 2026 review: the Swift 6.4 executable passed server-order preservation, archived-row filtering, duplicate-ID rejection, payload-size rejection, and malformed JSON checks. It is a processing fixture, not a claim about frame timing on a device.