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

Swift 5.5 Concurrency: how to serialize async Tasks to replace an OperationQueue with maxConcurrentOperationCount = 1?

I’m currently migrating my app to use the concurrency model in Swift. I want to serialize Tasks to make sure they are executed one after the other (no paralellism). In my use case, I want to listen to notifications posted by the NotificationCenter…
9
votes
1 answer

withThrowingTaskGroup - No calls to throwing functions occur within 'try' expression

Problem: I have the following function which shows a warning No calls to throwing functions occur within 'try' expression Questions: Why is this warning shown? (The code inside the task throws an error) What should I do to propagate the error to…
user1046037
  • 16,755
  • 12
  • 92
  • 138
9
votes
1 answer

Can I use actors in Swift to always call a function on the main thread?

I recently saw that Swift had introduced concurrency support with the Actor model in Swift 5.5. This model enables safe concurrent code to avoid data races when we have a shared, mutable state. I want to avoid main thread data races in my app's UI.…
Pranav Kasetti
  • 8,770
  • 2
  • 50
  • 71
8
votes
2 answers

How to convert DispatchQueue debounce to Swift Concurrency task?

I have an existing debouncer utility using DispatchQueue. It accepts a closure and executes it before the time threshold is met. It can be used like this: let limiter = Debouncer(limit: 5) var value = "" func sendToServer() { limiter.execute { …
TruMan1
  • 33,665
  • 59
  • 184
  • 335
7
votes
2 answers

How to execute a CPU-bound task in background using Swift Concurrency without blocking UI updates?

I have an ObservableObject which can do a CPU-bound heavy work: import Foundation import SwiftUI @MainActor final class Controller: ObservableObject { @Published private(set) var isComputing: Bool = false func compute() { if…
Louis Lac
  • 5,298
  • 1
  • 21
  • 36
7
votes
1 answer

Why Should SwiftUI View Models be Annotated with @MainActor?

I've been watching Apple's concurrency talks from WWDC21 as well as reading a ton of articles on Apple's concurrency updates; however, I cannot wrap my head around one thing: Why do people provide guidance that you should annotate view models with…
Nirvan Nagar
  • 189
  • 3
  • 11
7
votes
2 answers

Recurring function in Swift 5.5 using async/await

I want to keep firing a function 5 seconds after it completes. Previously I would use this at the end of the function: Timer.scheduledTimer(withTimeInterval: 5, repeats: false) { self.function() } But I am wanting to use Swift 5.5's async/await. If…
Darren
  • 10,182
  • 20
  • 95
  • 162
6
votes
1 answer

@MainActor closure does not seem to execute on the main thread deterministically

Consider the following, relatively simple Swift program: import Foundation func printContext(function: String = #function, line: Int = #line) { print("At \(function):\(line): Running on \(Thread.current) (main:…
fwcd
  • 81
  • 4
6
votes
1 answer

How to do asynchronous action with SwiftUI button

I want to click a button in SwiftUI that will trigger a JSON encoding action. This action is time consuming thus I need it to be async. I have already tried two solutions but they do not work. One major problem is how to create a async version of…
zxcheergo
  • 81
  • 1
  • 5
6
votes
1 answer

SwiftUI Combine - How to test waiting for a publisher's async result

I am listening for changes of a publisher, then fetching some data asynchronously in my pipeline and updating the view with the result. However, I am unsure how to make this testable. How can I best wait until the expectation has been…
Ryan
  • 145
  • 1
  • 6
6
votes
2 answers

swift async function is being run on the main thread in some cases when run from task

In this case the async function reads a file and returns the parsed contents. In my view I want to load the contents off of the main thread, and then update the view once complete. I've used this pattern in various places and noticed that in some…
Avba
  • 14,822
  • 20
  • 92
  • 192
5
votes
2 answers

Why does Swift not resume an asynchronous function on the same thread it was started?

In the introductory section of the Concurrency chapter of "The Swift Programming Language" I read: When an asynchronous function resumes, Swift doesn’t make any guarantee about which thread that function will run on. This surprised me. It seems…
meaning-matters
  • 21,929
  • 10
  • 82
  • 142
5
votes
0 answers

Why does swift not warn about this nonSendable global passing into different Task?

Consider the following code: class Cat { var name = "Tom" } class Globals { var cat = Cat() } let glob = Globals() func one () { Task {glob.cat.name="Max"} // Expected Warning about some nonSendable moving into a different concurrency…
JMC
  • 1,723
  • 1
  • 11
  • 20
5
votes
1 answer

Why are nested tasks not canceled when they parent task is cancelled?

I need to cancel all nested tasks I try to cancel their parent but nothing happens all nested tasks keep running. private var observationTask: Task? ... observationTask = Task { Task { for await users in list.$users.values…
Victor Kushnerov
  • 3,706
  • 27
  • 56
5
votes
1 answer

Make tasks in Swift concurrency run serially

I've a document based application that uses a struct for its main data/model. As the model is a property of (a subclass of) NSDocument it needs to be accessed from the main thread. So far all good. But some operations on the data can take quite a…
Remco Poelstra
  • 859
  • 6
  • 20
1
2
3
13 14