Beginning Networking with URLSession, Episode 3: More Modern Concurrency | Kodeco, the new raywenderlich.com

Continuing the coverage of Swift’s modern concurrency features.


This is a companion discussion topic for the original entry at https://www.kodeco.com/28450876-beginning-networking-with-urlsession/lessons/3

When you mark a method with @MainActor, does it mean that the whole method runs on the main thread or that its asynchronous work when finished working is then executed on the main thread. I suspect it’s the latter, but I just wanted to be clear.

I just completed the challenge and you explained the answer there.

So I guess when it comes to UI, if the method simply mutates a property that’s linked to UI, then the method can be marked with @MainActor. But if the method contains other work amongst a UI updating line, then mark only the line that should be run on the main thread. At least, that’s what I think that I’m understanding.

That sounds accurate and would be a sensible approach. To reaffirm what you seem to have a great grasp on:

If you have a method doing some complex computation, or perhaps a networking operation that could take a while and, upon completion, simply updates some UI-related properties, then mark just the UI updates as MainActor.

If the entire method is lean and mostly deals with UI work, mark the entire method as MainActor

:slight_smile:

1 Like