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
5
votes
1 answer

Difference of creating regular or detached Task from task-less context?

When creating a Task in a task-less context (e.g. from some random AppKit code), is there a difference between creating a detached or a regular task? For example, calling Task.detached or Task.init Since the task has no actor to inherit from, I…
user187676
5
votes
1 answer

MainActor vs MainActor(unsafe)

We can create a @MainActor Task like this: Task { @MainActor in print("hi") } But also with @MainActor(unsafe) like this: Task { @MainActor(unsafe) in print("hi") } What's the difference between these two methods?
George
  • 25,988
  • 10
  • 79
  • 133
5
votes
1 answer

The example code of task modifier of SwiftUI is confusing

Here is the code in Apple developer document。 let url = URL(string: "https://example.com")! @State private var message = "Loading..." var body: some View { Text(message) .task { do { var receivedLines =…
user11800374
5
votes
1 answer

Swift task is not running on main actor as expected

I have the following code in a simple Mac test project: @main class AppDelegate: NSObject, NSApplicationDelegate { func applicationDidFinishLaunching(_ aNotification: Notification) { print("are we initially on the main thread:…
Bill
  • 44,502
  • 24
  • 122
  • 213
5
votes
1 answer

Swift: how to wrap `completion` into an async/await?

I have a callback based API. func start(_ completion: @escaping () -> Void) I'd like to write an async/await wrapper on top of that API, deferring the implementation to original callback based API. func start() async { let task = Task() …
Isaaс Weisberg
  • 2,296
  • 2
  • 12
  • 28
5
votes
1 answer

Async autoreleasepool

I have a situation where I'm creating many Cocoa objects in a loop using async/await, and the memory spikes because the objects are only released when the loop is over (instead of every iteration). The solution would be to use an autoreleasepool.…
recaptcha
  • 253
  • 1
  • 7
5
votes
1 answer

Conforming @MainActor class, or actor, to Codable

How does one add Codable conformance to a class that needs to be isolated to the MainActor? For example, the following code gives compiler errors: @MainActor final class MyClass: Codable { var value: Int enum CodingKeys: String,…
Philip Pegden
  • 1,732
  • 1
  • 14
  • 33
4
votes
0 answers

Why is the "+" operator not Sendable

I have a snippet of code where I sum up the values of an AsyncSequence as seen below, but I get a warning on the plus operator: Converting non-sendable function value to '@Sendable (Int, Int) async -> Int' may introduce data races let asyncSequence…
TheLivingForce
  • 532
  • 9
  • 21
4
votes
1 answer

UI Update not triggered on Main Thread despite @MainActor annotation

I am annotating my function with @MainActor to ensure that it can be called from any async location safely to trigger a UI Update. Despite, I run into an error where, somehow, the UI Update seems to be attempted on a background thread, even though…
linus_hologram
  • 1,595
  • 13
  • 38
4
votes
1 answer

Reference to captured var in concurrently-executing code

I was trying out the new async/await pattern in swift and I came accross something which I found it confusing. struct ContentView: View { var body: some View { Text("Hello World!") .task { var num = 1 …
AKIL KUMAR
  • 287
  • 3
  • 8
4
votes
2 answers

Swift Concurrency: Notification Callbacks on @MainActor Objects

Context In a Mac app built with Swift 5.x and Xcode 14, I have a controller object. This object has several @Published properties that are observed by SwiftUI views, so I have placed the object on @MainActor like this: @MainActor final class…
Bryan
  • 4,628
  • 3
  • 36
  • 62
4
votes
2 answers

How come a MainActor isolated mutable stored property gives a sendable error?

I'm trying to conform a class to Sendable. I have some mutable stored properties which are causing issues. However, what I can't understand is that a MainActor isolated property doesn't allow my class to conform to Sendable. However, if I mark the…
Tometoyou
  • 7,792
  • 12
  • 62
  • 108
4
votes
1 answer

Swift concurrency multiple await for single async result

I have AuthorizationRequester which can be call from many places simultaneously, but only first call can run requestAuthorizationFromUser() (and wait dozen of seconds for user interaction) - rest of these calls should await for result from…
Michcio
  • 2,708
  • 19
  • 26
4
votes
4 answers

Swift: Map AsyncStream into another AsyncStream

Update The accepted answer did not directly answer the original question, but helped resolve the underlying issue I tried to solve: I wanted to map an AsyncStream (which is an AsyncSequence) into another AsyncSequence with element type T2. I added…
bzyr
  • 289
  • 1
  • 11
4
votes
3 answers

Integrate a blocking function into Swift async

I understand that an asynchronous Swift Task is not supposed to block (async worker threads must always make forward progress). If I have an otherwise 100% async Swift application but need to introduce some blocking tasks, what is the correct way to…
zaphoyd
  • 2,642
  • 1
  • 16
  • 22
1 2
3
13 14