The Wild

Migrate Legacy Swift Code to Modern Concurrency

· 6 min read · Mammals

In this article
  1. What You'll Need
  2. Step-by-Step
  3. Common Mistakes
  4. Tips
  5. Troubleshooting
  6. Frequently Asked Questions

Migrating legacy Swift code to modern concurrency (async/await, actors, and Sendable) eliminates callback pyramids, race conditions, and manual dispatch queue juggling. You'll get safer, more readable code that's easier to maintain. This guide walks through a practical, incremental migration path, assuming you're already on Swift 5.5+ (ideally Swift 5.7+ for full features) and Xcode 13.2+.

What You'll Need

  • Xcode 13.2 or later (Swift 5.5+); Xcode 14+ recommended for better diagnostics.
  • An existing Swift project with legacy concurrency patterns (completion handlers, DispatchQueue, delegate callbacks).
  • Basic familiarity with async/await syntax and actors.
  • Time to run the migration in small, testable increments.

Step-by-Step

  1. Enable strict concurrency checking. In Xcode, set the Swift compiler flag -strict-concurrency=complete (or in build settings: Strict Concurrency Checking to “Complete”). This surfaces potential data races and Sendable violations early. You'll see warnings and errors that guide your migration.
  2. Identify the highest-value targets. Look for completion-handler functions, especially those with nested callbacks or that are called from UI code. Use the compiler's “Convert to async” refactoring (Edit > Refactor > Convert to Async) on a single function first. This automatically transforms a completion handler into an async function that returns a value or throws.
  3. Convert one function at a time. For each function, replace the completion handler with an async signature. For example, change func fetchUser(completion: @escaping (User?, Error?) -> Void) to func fetchUser() async throws -> User. Inside, call the original completion-based API using withCheckedThrowingContinuation (or withUnsafeContinuation if you're certain of the callback behavior).
  4. Propagate async upward. After converting a function, update its call sites to use await. This may require making the calling function async as well. Work from the bottom up (leaf functions) to the top (view controllers or entry points).
  5. Replace DispatchQueue.main.async with MainActor. For UI updates, annotate the relevant class or method with @MainActor instead of manually dispatching to the main queue. For example, a view model that updates UI properties can be marked @MainActor entire class, or just the specific methods that touch UI.
  6. Introduce actors for shared mutable state. If you have a class that is accessed from multiple threads and has mutable properties, convert it to an actor. This automatically serializes access to its properties and methods, eliminating data races. For example, a cache or a session manager is a good actor candidate.
  7. Mark types as Sendable. When passing data across concurrency domains, the compiler must know it's safe. For value types (structs, enums), conformance to Sendable is often automatic if all properties are Sendable. For classes, you may need to make them immutable or use a lock/actor. Use @unchecked Sendable only as a last resort with careful justification.
  8. Refactor delegate callbacks to async sequences or continuations. For delegate patterns (like URLSessionDataDelegate), consider using AsyncStream to expose a stream of events, or wrap the delegate in a continuation. This is more involved but removes the delegate boilerplate.
  9. Update unit tests. Convert test methods that rely on expectations to use async/await directly. Xcode's XCTest supports async test methods, so you can simply mark them async throws and use await on the functions you're testing.
  10. Run the compiler and fix warnings iteratively. After each batch of changes, build and address any new concurrency warnings. The compiler will point out missing Sendable conformances, main-actor isolation issues, and data race risks. Fix these before moving on.

Common Mistakes

  • Converting everything at once. This leads to a massive, error-prone diff. Instead, migrate incrementally, keeping the app building and tests passing after each change.
  • Ignoring Sendable warnings. Passing non-Sendable types across actors or tasks can cause subtle data races. Always address Sendable conformance warnings rather than silencing them.
  • Using @unchecked Sendable as a shortcut. This bypasses compiler safety checks. Use it only when you've manually proven thread-safety (e.g., via a lock) and document why.
  • Misusing Task for fire-and-forget work. Creating unstructured tasks without storing the handle can lead to unexpected behavior. Use Task only when you need to start work from a synchronous context and manage its lifecycle.
  • Forgetting to propagate @MainActor. If a class is marked @MainActor, all its methods and properties are isolated to the main actor. Calling a non-isolated async function from it may cause a hop, which is fine, but forgetting to mark a class that touches UI leads to crashes.

Tips

  • Use the “Convert to Async” refactoring as a starting point, but review the generated code—it often uses continuations that can be simplified.
  • Prefer withCheckedThrowingContinuation over its unsafe variant; it will log warnings if the continuation is resumed more than once or not at all, which catches bugs.
  • For network calls, consider using async versions of URLSession methods (e.g., data(from:)) instead of wrapping completion handlers.
  • Use Task with @MainActor for UI updates from background tasks: Task { @MainActor in ... }.
  • Keep a running list of remaining legacy patterns (e.g., DispatchQueue.async, semaphores) and tackle them one by one.

Troubleshooting

  • Compiler errors about actor isolation. Read the error message carefully—it usually tells you which property or method is not isolated. Add @MainActor to the enclosing type or method, or make the property nonisolated if it's a constant.
  • Data races still occurring. If you see intermittent crashes, run the Thread Sanitizer (Product > Scheme > Edit Scheme > Diagnostics > Thread Sanitizer). It will pinpoint the exact line where a race occurs. Then, either make the type an actor or protect the data with a lock.
  • Deadlocks with continuations. If your app hangs, it's likely a continuation is never resumed. Check that the completion handler is called on all code paths, including error cases. Use withCheckedContinuation to get a runtime warning if it's not resumed.
  • “Converting function to async” fails. The refactoring tool may fail if the function has multiple completion handlers or complex control flow. In that case, manually rewrite the function using a continuation, and handle each callback separately.
  • Performance degradation. If you see a slowdown, it might be due to excessive actor hops. Use nonisolated for pure functions that don't access mutable state, and batch UI updates to avoid multiple main-actor hops.

Frequently Asked Questions

Can I mix async/await with completion handlers?

Yes, you can call async functions from completion-handler code by using Task to create a new task, and you can wrap completion handlers with continuations to make them async. However, it's best to migrate gradually, keeping the interface consistent where possible.

Do I need to migrate all at once?

No. Swift allows async functions to be called from synchronous contexts using Task, and you can keep legacy code alongside new code. However, the more you migrate, the easier it becomes to reason about concurrency.

What's the difference between actors and classes?

Actors protect their mutable state by serializing access to their methods and properties. Classes do not, unless you add locks or other synchronization. Actors are preferred for shared mutable state in concurrent code.

How do I handle a delegate that I can't convert to async?

Wrap the delegate in an AsyncStream or use a continuation that you resume when the delegate method is called. This lets you consume the delegate events asynchronously.

Is @MainActor the same as DispatchQueue.main.async?

Not exactly. @MainActor is a compile-time guarantee that code runs on the main actor, eliminating the need for manual dispatch. It also allows the compiler to catch main-thread violations.

What if I have a large legacy codebase?

Start with the most critical or frequently used functions, and migrate incrementally. Use the compiler's concurrency checking to guide you, and don't be afraid to leave some code as-is until you have time to refactor it properly.