Questions tagged [swift-concurrency]

For concurrency language features in Swift, such as async and await. This tag also includes other concurrency features such as actors, Sendable closures, and more.

Swift concurrency with async-await can allow for more readable asynchronous code, an improvement over traditional completion handler closure patterns. “Swift concurrency” also include “actors” (a new object type designed to avoid data races), “tasks” (an object that wraps an asynchronous task, often useful for launching asynchronous action from synchronous context, managing dependencies, or when implementing cancelation support), “sendable” types, etc.

Swift concurrency was introduced in Swift 5.5 in Xcode 13 (supporting macOS 12 and iOS 15), but Xcode 13.3 introduced some backward-compatibility with recent OS versions (e.g., back to iOS 13).

Swift concurrency offers mechanism to retire completion handler closure patterns. In many cases, it obviates the need for code written for and .

References

200 questions
39
votes
4 answers

Swift await/async - how to wait synchronously for an async task to complete?

I'm bridging the sync/async worlds in Swift and doing incremental adoption of async/await. I'm trying to invoke an async function that returns a value from a non async function. I understand that explicit use of Task is the way to do that, as…
gds
  • 578
  • 1
  • 4
  • 7
31
votes
3 answers

How to prevent actor reentrancy resulting in duplicative requests?

In WWDC 2021 video, Protect mutable state with Swift actors, they provide the following code snippet: actor ImageDownloader { private var cache: [URL: Image] = [:] func image(from url: URL) async throws -> Image? { if let cached =…
Rob
  • 415,655
  • 72
  • 787
  • 1,044
30
votes
2 answers

Swift, actor: Actor-isolated property 'scanning' can not be mutated from a non-isolated context

I have an actor: actor StatesActor { var job1sActive:Bool = false ... } I have an object that uses that actor: class MyObj { let myStates = StatesActor() func job1() async { myStates.job1IsActive = true …
zumzum
  • 17,984
  • 26
  • 111
  • 172
29
votes
5 answers

`Task` blocks main thread when calling async function inside

I have an ObservableObject class and a SwiftUI view. When a button is tapped, I create a Task and call populate (an async function) from within it. I thought this would execute populate on a background thread but instead the entire UI freezes.…
aheze
  • 24,434
  • 8
  • 68
  • 125
29
votes
2 answers

async/await, Task and [weak self]

Okay so we all know that in traditional concurrency in Swift, if you are performing (for example) a network request inside a class, and in the completion of that request you reference a function that belongs to that class, you must pass [weak self]…
Matt Beaney
  • 460
  • 4
  • 15
24
votes
1 answer

Call to main actor-isolated instance method XXX in a synchronous nonisolated context

I am trying to add an async do/catch/defer action to a UIButton. However, if I just call a method in the defer block, I get Call to main actor-isolated instance method XXX in a synchronous nonisolated context error. The workaround I found is to wrap…
Jack Guo
  • 3,959
  • 8
  • 39
  • 60
21
votes
2 answers

How to await x seconds with async await Swift 5.5

How do I use the new Swift 5.5 await keyword to wait for a duration of time? Normally, with completion handlers, you would have something like this by using DispatchQueue's asyncAfter(deadline:execute:): func someLongTask(completion: @escaping (Int)…
George
  • 25,988
  • 10
  • 79
  • 133
20
votes
1 answer

Maximum number of threads with async-await task groups

My intent is to understand the “cooperative thread pool” used by Swift 5.5’s async-await, and how task groups automatically constrain the degree of concurrency: Consider the following task group code, doing 32 calculations in parallel: func…
Rob
  • 415,655
  • 72
  • 787
  • 1,044
20
votes
1 answer

How to access an actor-isolated property

I try to check the actor's behavior. This is a new feature provided by Swift5.5. I've created a playground with an example code from the official documentation swift.org: import Foundation actor TemperatureLogger { let label:…
Denis Kreshikhin
  • 8,856
  • 9
  • 52
  • 84
16
votes
1 answer

How to constrain concurrency (like `maxConcurrentOperationCount`) with Swift Concurrency?

I am trying to perform a series of network requests and would like to limit the number of concurrent tasks in the new Swift Concurrency system. With operation queues we would use maxConcurrentOperationCount. In Combine, flatMap(maxPublishers:_:).…
Rob
  • 415,655
  • 72
  • 787
  • 1,044
14
votes
1 answer

How do I initialize a global variable with @MainActor?

I would like to have some sort of global variable that is synchronized using @MainActor. Here's an example struct: @MainActor struct Foo {} I'd like to have a global variable something like this: let foo = Foo() However, this does not compile and…
Wil Gieseler
  • 1,893
  • 1
  • 17
  • 18
12
votes
1 answer

Converting non-sendable function value may introduce data races

I have a simple piece of code: struct ContentView: View { var body: some View { Text("Hello world!") .task { await myAsyncFunc() } } private func myAsyncFunc() async {} } This compiles…
George
  • 25,988
  • 10
  • 79
  • 133
11
votes
3 answers

How to properly cancel Swift async/await function

I have watched Explore structured concurrency in Swift video and other relevant videos / articles / books I was able to find (swift by Sundell, hacking with swift, Ray Renderlich), but all examples there are very trivial - async functions usually…
10
votes
1 answer

Is there a difference between "@MainActor in" and "MainActor.run"?

Is there any difference between: Task { await MainActor.run { ... } } and Task { @MainActor in ... }
Philip Pegden
  • 1,732
  • 1
  • 14
  • 33
10
votes
1 answer

Swift 5.5 Concurrency: creating a task with custom error type

I need to use my own custom error enum in tasks that I create: enum MyError: Error { case someError } var myTask: Task = Task { () throws -> MyModel in // in case of an error: // throw .someError …
JAHelia
  • 6,934
  • 17
  • 74
  • 134
1
2 3
13 14