Swift Concurrency Resources:
Forums tags: Concurrency
The Swift Programming Language > Concurrency documentation
Migrating to Swift 6 documentation
WWDC 2022 Session 110351 Eliminate data races using Swift Concurrency — This ‘sailing on the sea of concurrency’ talk is a great introduction to the fundamentals.
WWDC 2021 Session 10134 Explore structured concurrency in Swift — The table that starts rolling out at around 25:45 is really helpful.
Swift Async Algorithms package
Swift Concurrency Proposal Index DevForum post
Why is flow control important? forums post
Matt Massicotte’s blog
Dispatch Resources:
Forums tags: Dispatch
Dispatch documentation — Note that the Swift API and C API, while generally aligned, are different in many details. Make sure you select the right language at the top of the page.
Dispatch man pages — While the standard Dispatch documentation is good, you can still find some great tidbits in the man pages. See Reading UNIX Manual Pages. Start by reading dispatch in section 3.
WWDC 2015 Session 718 Building Responsive and Efficient Apps with GCD [1]
WWDC 2017 Session 706 Modernizing Grand Central Dispatch Usage [1]
Avoid Dispatch Global Concurrent Queues forums post
Waiting for an Async Result in a Synchronous Function forums post
Share and Enjoy
—
Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@" + "apple.com"
[1] These videos may or may not be available from Apple. If not, the URL should help you locate other sources of this info.
Concurrency
RSS for tagConcurrency is the notion of multiple things happening at the same time.
Posts under Concurrency tag
115 Posts
Selecting any option will automatically load the page
Post
Replies
Boosts
Views
Activity
App intent has a perform method that is async and can throw an error, but I can't find a way to actually await the result and catch the error if needed.
If I convert this working but non-waiting, non-catching code:
Button("Go", intent: MyIntent())
to this (so I can control awaiting and error handling):
Button("Go") {
Task {
do {
try await MyIntent().perform() // 👈
} catch {
print(error)
}
}
}
It crashes:
AppDependency with key "foo" of type Bar.Type was not initialized prior to access. Dependency values can only be accessed inside of the intent perform flow and within types conforming to _SupportsAppDependencies unless the value of the dependency is manually set prior to access.
Although it is invalid since the first version is working like a charm and dependencies are registered in the @main App init method and it is in the perform flow.
So how can we await the result of the AppIntent and handle the errors if needed in the app? Should I re-invent the Dependency mechanism?
Hello,
Regarding EKEventStore, the WWDC session mentions that “you should only have one of these for your application.”
In my app, I need to use the instance on both the main thread and a background thread, and I would like to share a single instance across them.
However, EKEventStore is a non-sendable type, so it cannot be shared across different isolation domains.
I would like to know what the recommended best practice is for this situation.
Also, do I need to protect the instance from data races by using a lock?
Thank you.
Is the pseudocode below thread-safe? Imagine that the Main thread sets the CAMetalLayer's drawableSize to a new size meanwhile the rendering thread is in the middle of rendering into an existing MTLDrawable which does still have the old size.
Is the change of metalLayer.drawableSize thread-safe in the sense that I can present an old MTLDrawable which has a different resolution than the current value of metalLayer.drawableSize? I assume that setting the drawableSize property informs Metal that the next MTLDrawable offered by the CAMetalLayer should have the new size, right?
Is it valid to assume that "metalLayer.drawableSize = newSize" and "metalLayer.nextDrawable()" are internally synchronized, so it cannot happen that metalLayer.nextDrawable() would produce e.g. a MTLDrawable with the old width but with the new height (or a completely invalid resolution due to potential race conditions)?
func onWindowResized(newSize: CGSize) {
// Called on the Main thread
metalLayer.drawableSize = newSize
}
func onVsync(drawable: MTLDrawable) {
// Called on a background rendering thread
renderer.renderInto(drawable: drawable)
}
I encountered a concurrency compilation warning when calling the TranslationSession.translations(from: [TranslationSession.Request]) API, and I'm don't know how to resolve it. I reviewed the official demo, but it appears identical.
Hi,
I played around the last days with the new NetworkConnection API from Network framework that supports structured concurrency. I discovered a behavior, which is unexpected from my understanding.
Let's say you have a dead endpoint or something that does not exist. Something where you receive a noSuchRecord error. When I then try to send data, I would expect that the send function throws an error but this does not happen. The function now suspends indefinitely which is well not a great behavior.
Example simplified:
func send() async {
let connection = NetworkConnection(to: .hostPort(host: "apple.co.com", port: 8080)) {
TCP()
}
do {
try await connection.send("Hello World!".raw)
} catch {
print(error)
}
}
I'm not sure if this is the intended behavior or how this should be handled.
Thanks and best regards,
Vinz
We're experiencing crashes in our production iOS app related to Apple's DeviceCheck framework. The crash occurs in DCAnalytics internal performance tracking, affecting some specific versions of iOS 18 (18.4.1, 18.5.0).
Crash Signature
CoreFoundation: -[__NSDictionaryM setObject:forKeyedSubscript:] + 460
DeviceCheck: -[DCAnalytics sendPerformanceForCategory:eventType:] + 236
Observed Patterns
Scenario 1 - Token Generation:
Crashed: com.appQueue
EXC_BAD_ACCESS KERN_INVALID_ADDRESS 0x0000000000000010
DeviceCheck: -[DCDevice generateTokenWithCompletionHandler:]
Thread: Background dispatch queue
Scenario 2 - Support Check:
Crashed: com.apple.main-thread
EXC_BAD_ACCESS KERN_INVALID_ADDRESS 0x0000000000000008
DeviceCheck: -[DCDevice _isSupportedReturningError:]
DeviceCheck: -[DCDevice isSupported]
Thread: Main thread
Root Cause Analysis
The DCAnalytics component within DeviceCheck attempts to insert a nil value into an NSMutableDictionary when recording performance metrics, indicating missing nil validation before dictionary operations.
Reproduction Context
Crashes occur during standard DeviceCheck API usage:
Calling DCDevice.isSupported property
Calling DCDevice.generateToken(completionHandler:) (triggered by Firebase App Check SDK)
Both operations invoke internal analytics that fail with nil insertion attempts.
Concurrency Considerations
We've implemented sequential access guards around DeviceCheck token generation to prevent race conditions, yet crashes persist. This suggests the issue likely originates within the DeviceCheck framework's internal implementation rather than concurrent access from our application code.
Note: Scenario 2 occurs through Firebase SDK's App Check integration, which internally uses DeviceCheck for attestation.
Request
Can Apple engineering confirm if this is a known issue with DeviceCheck's analytics subsystem? Is there a recommended workaround to disable DCAnalytics or ensure thread-safe DeviceCheck API usage?
Any guidance on preventing these crashes would be appreciated.
I have been working on an app for the past few months, and one issue that I have encountered a few times is an error where quick subsequent deletions cause issues with detached tasks that are triggered from some user actions.
Inside a Task.detached, I am building an isolated model context, querying for LineItems, then iterating over those items. The crash happens when accessing a Transaction property through a relationship.
var byTransactionId: [UUID: [LineItem]] {
return Dictionary(grouping: self) { item in
item.transaction?.id ?? UUID()
}
}
In this case, the transaction has been deleted, but the relationship existed when the fetch occurred, so the transaction value is non-nil. The crash occurs when accessing the id. This is the error.
SwiftData/BackingData.swift:1035: Fatal error: This model instance was invalidated because its backing data could no longer be found the store. PersistentIdentifier(id: SwiftData.PersistentIdentifier.ID(backing: SwiftData.PersistentIdentifier.PersistentIdentifierBacking.managedObjectID(0xb43fea2c4bc3b3f5 <x-coredata://A9EFB8E3-CB47-48B2-A7C4-6EEA25D27E2E/Transaction/p1756>)))
I see other posts about this error and am exploring some suggestions, but if anyone has any thoughts, they would be appreciated.
I occasionally get this error in Xcode’s console:
Potential Structural Swift Concurrency Issue: unsafeForcedSync called from Swift Concurrent context.
What does this mean, and how can I resolve it? Googling it doesn’t turn up any results.
This doesn't crash the app - it’s just an error diagnostic that I see in the Xcode console. The app keeps running before and after the issue.
Is there a way I can set a breakpoint to catch this where it happens?
I got several reports about our TestFlight app crashing unconditionally on 2 devices (iOS 18.1 and iOS 18.3.1) on app start with the following reason:
Termination Reason: DYLD 4 Symbol missing
Symbol not found: _$sScIsE4next7ElementQzSgyYa7FailureQzYKF
(terminated at launch; ignore backtrace)
The symbol in question demangles to
(extension in Swift):Swift.AsyncIteratorProtocol.next() async throws(A.Failure) -> A.Element?
Our deploy target is iOS 18.0, this symbol was introduced in Swift 6.0, we're using latest Xcode 16 now - everything should be working, but for some reason aren't.
Since this symbol is quite rarely used directly, I was able to pinpoint the exact place in code related to it. Few days ago I added the following code to our app library (details omitted):
public struct AsyncRecoveringStream<Base: AsyncSequence>: AsyncSequence {
...
public struct AsyncIterator: AsyncIteratorProtocol {
...
public mutating func next(isolation actor: isolated (any Actor)? = #isolation) async throws(Failure) -> Element? {
...
}
}
}
I tried to switch to Xcode 26 - it was still crashing on affected phone. Then I changed next(isolation:) to its older version, next():
public mutating func next() async throws(Failure) -> Element?
And there crashes are gone. However, this change is a somewhat problematic, since I either have to lower Swift version of our library from 6 to 5 and we loose concurrency checks and typed throws or I'm loosing tests due to Swift compiler crash. Performance is also affected, but it's not that critical for our case.
Why is this crash happening? How can I solve this problem or elegantly work around it?
Thank you!
2025-10-09_17-13-31.7885_+0100-23e00e377f9d43422558d069818879042d4c5c2e.crash
Hi everyone,
I’m trying to register fonts system-wide using CTFontManagerRegisterFontURLs with the .persistent scope. The fonts are delivered through Apple-Hosted Background Assets (since On-Demand Resources are deprecated).
Process-level registration works perfectly, but persistent registration triggers a system “Install Fonts” prompt, and tapping Install causes the app to crash immediately.
I’m wondering if anyone has successfully used Apple-Hosted Background Assets to provide persistent, system-wide installable fonts, or if this is a current OS limitation/bug.
What I Expect
Fonts delivered through Apple-Hosted Background Assets should be eligible for system-wide installation
Tap “Install” should install fonts into Settings → Fonts just like app-bundled or ODR fonts
App should not crash
Why This Matters
According to:
WWDC 2019: Font Management and Text Scaling
Developers can build font provider apps that install fonts system-wide, using bundled or On-Demand Resources.
WWDC 2025: Discover Apple-Hosted Background Assets
On-Demand Resources are deprecated, and AHBAs are the modern replacement.
Therefore, persistent font installation via Apple-Hosted Background Assets appears to be the intended path moving forward.
Question
Is this a known limitation or bug in iOS?
Should .persistent font installation work with Apple-Hosted Background Assets?
Do we need additional entitlement, manifest configuration, or packaging rules?
Any guidance or confirmation from Apple engineers would be greatly appreciated.
Additional Info
I submitted a Feedback including a minimal reproducible sample project:
FB21109320
Topic:
App & System Services
SubTopic:
Processes & Concurrency
Tags:
Core Text
Background Assets
Typography
Concurrency
Hi everyone,
I'm looking for the correct architectural guidance for my SwiftData implementation.
In my Swift project, I have dedicated async functions for adding, editing, and deleting each of my four models. I created these functions specifically to run certain logic whenever these operations occur. Since these functions are asynchronous, I call them from the UI (e.g., from a button press) by wrapping them in a Task.
I've gone through three different approaches and am now stuck.
Approach 1: @MainActor Functions
Initially, my functions were marked with @MainActor and worked on the main ModelContext. This worked perfectly until I added support for App Intents and Widgets, which caused the app to crash with data race errors.
Approach 2: Passing ModelContext as a Parameter
To solve the crashes, I decided to have each function receive a ModelContext as a parameter. My SwiftUI views passed the main context (which they get from @Environment(\.modelContext)), while the App Intents and Widgets created and passed in their own private context. However, this approach still caused the app to crash sometimes due to data race errors, especially during actions triggered from the main UI.
Approach 3: Creating a New Context in Each Function
I moved to a third approach where each function creates its own ModelContext to work on. This has successfully stopped all crashes. However, now the UI actions don't always react or update. For example, when an object is added, deleted, or edited, the change isn't reflected in the UI. I suspect this is because the main context (driving the UI) hasn't been updated yet, or because the async function hasn't finished its work.
My Question
I'm not sure what to do or what the correct logic should be. How should I structure my data operations to support the main UI, Widgets, and App Intents without causing crashes or UI update failures?
Here is the relevant code using my third (and current) approach. I've shortened the helper functions for brevity.
// MARK: - SwiftData Operations
extension DatabaseManager {
/// Creates a new assignment and saves it to the database.
public func createAssignment(
name: String, deadline: Date, notes: AttributedString,
forCourseID courseID: UUID, /*...other params...*/
) async throws -> AssignmentModel {
do {
let context = ModelContext(container)
guard let course = findCourse(byID: courseID, in: context) else {
throw DatabaseManagerError.itemNotFound
}
let newAssignment = AssignmentModel(
name: name, deadline: deadline, notes: notes, course: course, /*...other properties...*/
)
context.insert(newAssignment)
try context.save()
// Schedule notifications and add to calendar
_ = try? await scheduleReminder(for: newAssignment)
newAssignment.calendarEventIDs = await CalendarManager.shared.addEventToCalendar(for: newAssignment)
try context.save()
await MainActor.run {
WidgetCenter.shared.reloadTimelines(ofKind: "AppWidget")
}
return newAssignment
} catch {
throw DatabaseManagerError.saveFailed
}
}
/// Finds a specific course by its ID in a given context.
public func findCourse(byID id: UUID, in context: ModelContext) -> CourseModel? {
let predicate = #Predicate<CourseModel> { $0.id == id }
let fetchDescriptor = FetchDescriptor<CourseModel>(predicate: predicate)
return try? context.fetch(fetchDescriptor).first
}
}
// MARK: - Helper Functions (Implementations omitted for brevity)
/// Schedules a local user notification for an event.
func scheduleReminder(for assignment: AssignmentModel) async throws -> String {
// ... Full implementation to create and schedule a UNNotificationRequest
return UUID().uuidString
}
/// Creates a new event in the user's selected calendars.
extension CalendarManager {
func addEventToCalendar(for assignment: AssignmentModel) async -> [String] {
// ... Full implementation to create and save an EKEvent
return [UUID().uuidString]
}
}
Thank you for your help.
Hello! We are in the progress of migrating a large Swift 5.10 legacy code base over to use Swift 6.0 with Strict Concurrency checking.
We have already stumbled across a few weird edge cases where the "guaranteed" @MainActor isolation is violated (such as with @objc #selector methods used with NotificationCenter).
However, we recently found a new scenario where our app crashes accessing main actor isolated state on a background thread, and it was surprising that the compiler couldn't warn us.
Minimal reproducible example:
class ViewController: UIViewController {
var isolatedStateString = "Some main actor isolated state"
override func viewDidLoad() {
exampleMethod()
}
/// Note: A `@MainActor` isolated method in a `@MainActor` isolated class.
func exampleMethod() {
testAsyncMethod() { [weak self] in
// !!! Crash !!!
MainActor.assertIsolated()
// This callback inherits @MainActor from the class definition, but it is called on a background thread.
// It is an error to mutate main actor isolated state off the main thread...
self?.isolatedStateString = "Let me mutate my isolated state"
}
}
func testAsyncMethod(completionHandler: (@escaping () -> Void)) {
let group = DispatchGroup()
let queue = DispatchQueue.global()
// The compiler is totally fine with calling this on a background thread.
group.notify(queue: queue) {
completionHandler()
}
// The below code at least gives us a compiler warning to add `@Sendable` to our closure argument, which is helpful.
// DispatchQueue.global().async {
// completionHandler()
// }
}
}
The problem:
In the above code, the completionHandler implementation inherits main actor isolation from the UIViewController class.
However, when we call exampleMethod(), we crash because the completionHandler is called on a background thread via the DispatchGroup.notify(queue:).
If were to instead use DispatchQueue.global().async (snippet at the bottom of the sample), the compiler helpfully warns us that completionHandler must be Sendable.
Unfortunately, DispatchGroup's notify gives us no such compiler warnings. Thus, we crash at runtime.
So my questions are:
Why can't the compiler warn us about a potential problem with DispatchGroup().notify(queue:) like it can with DispatchQueue.global().async?
How can we address this problem in a holistic way in our app, as it's a very simple mistake to make (with very bad consequences) while we migrate off GCD?
I'm sure the broader answer here is "don't mix GCD and Concurrency", but unfortunately that's a little unavoidable as we migrate our large legacy code base! 🙂
I have a visionOS app where I instantiate ARKitSession and various providers (HandTrackingProvider and WorldTrackingProvider) in my appModel. That way, I can pass these providers to a Task which runs a gRPC server for sending the data from these providers to a client. When the users enters the immersive space of the app, the ARKitSession will run the providers if they are not running already.
I am now trying to implement the AccessoryTrackingProvider with the PSVR sense controllers but it does not fit with my current framework because the controllers may not be connected when the ARKitSession.run function is called. So I need to find a new place to start the session.
My question is, if I already have a session which is running the hand and world tracking providers, can I start another session to run the accessory tracking? Should they all be running on the same session?
Is there a way to stop the session and restart it when the controllers are connected? When I tried this, I get an error that says "It is not possible to re-run a stopped data provider (<ar_hand_tracking_provider_t: " but if I instantiate a new HandTrackingProvider, then the one that got passed to the gRPC task would no longer be the one running in the new session.
Any advice on how best to manage the various providers and ARKit sessions would be greatly appreciated.
Since Xcode 26 our tests are crashing due to the Main Thread not being able to deallocate WKNavigationResponse.
Following an example:
import Foundation
import WebKit
final class WKNavigationResponeMock: WKNavigationResponse {
private let urlResponse: URLResponse
override var response: URLResponse { urlResponse }
init(urlResponse: URLResponse) {
self.urlResponse = urlResponse
super.init()
}
convenience init(httpUrlResponse: HTTPURLResponse) {
self.init(urlResponse: httpUrlResponse)
}
convenience init?(url: URL, statusCode: Int) {
guard let httpURLResponse = HTTPURLResponse(url: url, statusCode: statusCode, httpVersion: nil, headerFields: nil) else {
return nil
}
self.init(httpUrlResponse: httpURLResponse)
}
}
import WebKit
import XCTest
final class ExampleTests: XCTestCase {
@MainActor func testAllocAndDeallocWKNavigationResponse() {
let expectedURL = URL(string: "https://galaxus.ch/")!
let expectedStatusCode = 404
let instance = WKNavigationResponeMock()
// here it should dealloc/deinit `instance` automatically
}
Here the call stack:
Thread 0 Crashed:: Dispatch queue: com.apple.main-thread
0 CoreFoundation 0x101f3dd54 CFRetain.cold.1 + 16
1 CoreFoundation 0x101e14860 CFRetain + 104
2 WebKit 0x10864dd24 -[WKNavigationResponse dealloc] + 52
Hi,
I am programming in C and would like to use Grand Central Dispatch for parallel computing (I mostly do physics based simulations). I remember there used to be example codes provided by Apple, but can't find those now. Instead I get the plain documentation. May anyone point me to the correct resources? It will be greatly appreciated. Thanks ☺.
Error: "Attrubute can only be applied to types not declarations" on line 2 : @unchecked
@unchecked
enum ReminderRow : Hashable, Sendable {
case date
case notes
case time
case title
var imageName : String? {
switch self {
case .date: return "calendar.circle"
case .notes: return "square.and.pencil"
case .time: return "clock"
default : return nil
}
}
var image : UIImage? {
guard let imageName else { return nil }
let configuration = UIImage.SymbolConfiguration(textStyle: .headline)
return UIImage(systemName: imageName, withConfiguration: configuration)
}
var textStyle : UIFont.TextStyle {
switch self {
case .title : return .headline
default : return .subheadline
}
}
}
Hi, I've got this view model that will do a search using a database of keywords. It worked fine when the SearchEngine wasn't an actor but a regular class and the SearchResult wasn't a Sendable. But when I changed them, it returned Type of expression is ambiguous without a type annotation error at line 21 ( searchTask = Task {). What did I do wrong here? Thanks.
protocol SearchableEngine: Actor {
func searchOrSuggest(from query: String) -> SearchResult?
func setValidTitles(_ validTitles: [String])
}
@MainActor
final class SearchViewModel: ObservableObject {
@Published var showSuggestion: Bool = false
@Published var searchedTitles: [String] = []
@Published var suggestedKeyword: String? = nil
private var searchTask: Task<Void, Never>?
private let searchEngine: SearchableEngine
init(searchEngine: SearchableEngine) {
self.searchEngine = searchEngine
}
func search(_ text: String) {
searchTask?.cancel()
searchTask = Task {
guard !Task.isCancelled else { return }
let searchResult = await searchEngine.searchOrSuggest(from: text) ?? .notFound
guard !Task.isCancelled else { return }
await MainActor.run {
switch searchResult {
case let .searchItems(_, items):
showSuggestion = false
searchedTitles = items.map(\.title)
suggestedKeyword = nil
case let .suggestion(keyword, _, items):
showSuggestion = true
searchedTitles = items.map(\.title)
suggestedKeyword = keyword
case .notFound:
showSuggestion = false
searchedTitles = []
suggestedKeyword = nil
}
}
}
}
}
This comes up over and over, here on the forums and elsewhere, so I thought I’d post my take on it. If you have questions or comments, start a new thread here on the forums. Put it in the App & System Services > Processes & Concurrency subtopic and tag it with Concurrency.
Share and Enjoy
—
Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@" + "apple.com"
Waiting for an Async Result in a Synchronous Function
On Apple platforms there is no good way for a synchronous function to wait on the result of an asynchronous function.
Lemme say that again, with emphasis…
On Apple platforms there is no good way for a synchronous function to wait on the result of an asynchronous function.
This post dives into the details of this reality.
Prime Offender
Imagine you have an asynchronous function and you want to call it from a synchronous function:
func someAsynchronous(input: Int, completionHandler: @escaping @Sendable (_ output: Int) -> Void) {
… processes `input` asynchronously …
… when its done, calls the completion handler with the result …
}
func mySynchronous(input: Int) -> Int {
… calls `someAsynchronous(…)` …
… waits for it to finish …
… results the result …
}
There’s no good way to achieve this goal on Apple platforms. Every approach you might try has fundamental problems.
A common approach is to do this working using a Dispatch semaphore:
func mySynchronous(input: Int) -> Int {
fatalError("DO NOT WRITE CODE LIKE THIS")
let sem = DispatchSemaphore(value: 0)
var result: Int? = nil
someAsynchronous(input: input) { output in
result = output
sem.signal()
}
sem.wait()
return result!
}
Note This code produces a warning in the Swift 5 language mode which turns into an error in the Swift 6 language mode. You can suppress that warning with, say, a Mutex. I didn’t do that here because I’m focused on a more fundamental issue here.
This code works, up to a point. But it has unavoidable problems, ones that don’t show up in a basic test but can show up in the real world. The two biggest ones are:
Priority inversion
Thread pools
I’ll cover each in turn.
Priority Inversion
Apple platforms have a mechanism that helps to prevent priority inversion by boosting the priority of a thread if it holds a resource that’s needed by a higher-priority thread. The code above defeats that mechanism because there’s no way for the system to know that the threads running the work started by someAsynchronous(…) are being waited on by the thread blocked in mySynchronous(…). So if that blocked thread has a high-priority, the system can’t boost the priority of the threads doing the work.
This problem usually manifests in your app failing to meet real-time goals. An obvious example of this is scrolling. If you call mySynchronous(…) from the main thread, it might end up waiting longer than it should, resulting in noticeable hitches in the scrolling.
Threads Pools
A synchronous function, like mySynchronous(…) in the example above, can be called by any thread. If the thread is part of a thread pool, it consumes a valuable resource — that is, a thread from the pool — for a long period of time. The raises the possibility of thread exhaustion, that is, where the pool runs out of threads.
There are two common thread pools on Apple platforms:
Dispatch
Swift concurrency
These respond to this issue in different ways, both of which can cause you problems.
Dispatch can choose to over-commit, that is, start a new worker thread to get work done while you’re hogging its existing worker threads. This causes two problems:
It can lead to thread explosion, where Dispatch starts dozens and dozens of threads, which all end up blocked. This is a huge waste of resources, notably memory.
Dispatch has an hard limit to how many worker threads it will create. If you cause it to over-commit too much, you’ll eventually hit that limit, putting you in the thread exhaustion state.
In contrast, Swift concurrency’s thread pool doesn’t over-commit. It typically has one thread per CPU core. If you block one of those threads in code like mySynchronous(…), you limit its ability to get work done. If you do it too much, you end up in the thread exhaustion state.
WARNING Thread exhaustion may seem like just a performance problem, but that’s not the case. It’s possible for thread exhaustion to lead to a deadlock, which blocks all thread pool work in your process forever.
There’s a trade-off here. Swift concurrency doesn’t over-commit, so it can’t suffer from thread explosion but is more likely deadlock, and vice versa for Dispatch.
Bargaining
Code like the mySynchronous(…) function shown above is fundamentally problematic. I hope that the above has got you past the denial stage of this analysis. Now let’s discuss your bargaining options (-:
Most folks don’t set out to write code like mySynchronous(…). Rather, they’re working on an existing codebase and they get to a point where they have to synchronously wait for an asynchronous result. At that point they have the choice of writing code like this or doing a major refactor.
For example, imagine you’re calling mySynchronous(…) from the main thread in order to update a view. You could go down the problematic path, or you could refactor your code so that:
The current value is always available to the main thread.
The asynchronous code updates that value in an observable way.
The main thread code responds to that notification by updating the view from the current value.
This refactoring may or may not be feasible given your product’s current architecture and timeline. And if that’s the case, you might end up deploying code like mySynchronous(…). All engineering is about trade-offs. However, don’t fool yourself into thinking that this code is correct. Rather, make a note to revisit this choice in the future.
Async to Async
Finally, I want to clarify that the above is about synchronous functions. If you have a Swift async function, there is a good path forward. For example:
func mySwiftAsync(input: Int) async -> Int {
let result = await withCheckedContinuation { continuation in
someAsynchronous(input: input) { output in
continuation.resume(returning: output)
}
}
return result
}
This looks like it’s blocking the current thread waiting for the result, but that’s not what happens under the covers. Rather, the Swift concurrency worker thread that calls mySwiftAsync(…) will return to the thread pool at the await. Later, when someAsynchronous(…) calls the completion handler and you resume the continuation, Swift will grab a worker thread from the pool to continue running mySwiftAsync(…).
This is absolutely normal and doesn’t cause the sorts of problems you see with mySynchronous(…).
IMPORTANT To keep things simple I didn’t implement cancellation in mySwiftAsync(…). In a real product it’s important to support cancellation in code like this. See the withTaskCancellationHandler(operation:onCancel:isolation:) function for the details.
I have two apps in which I have fixed warnings on Sendable, however there's one app where I did not and it looks like the rent's come due with Xcode 26.0, as I am getting over 100 warnings about Sendable. On a lark, I let the AI work on the warnings. There were so many that I ran out of free ChatGPT time and had to wait 24 hours. But today I cleared every remaining warning, but did the app still work? I figured I'd have to trash this code and do it by hand. But to my surprise, the app is working properly so far. More testing needs to be done and I need to dig into the code to make sure it's right, but so far, so good.