Instruction

Heads up... You’re accessing parts of this content for free, with some sections shown as scrambled text.

Heads up... You’re accessing parts of this content for free, with some sections shown as scrambled text.

Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.

Unlock now

In the previous lesson, you learned about asynchronous programming in Swift; by using the async and await keywords, the code becomes simple to write and easy to read.

Now, it’s time to consider other scenarios, such as shared state and race conditions.

Shared State

Shared state adheres to the SOLID Single Responsibility Principle. This principle explains that classes should have only one job.

Race Conditions

Stateful representation of a feature should be in one place, which means that many different objects can access the data.

Actors

Enter: Actors! Swift actors address many of the common race condition challenges by:

What Are Actors?

An actor in Swift is a reference type that provides thread-safe access to its mutable state. Unlike classes and structs, actors automatically serialize access to their data. This prevents simultaneous modifications from multiple threads.

Xiuhacu Tmkuqfx Bsebroj Ufwujh Gabjapvovcm Yuhxkabm Vim qeefz-ow Zig fuemn-ic Luezr-of deqeegevawoez Qavaliqgi ry. Molee Zabea xnxi Dulihilla fxto Yuqofofri hzdi Xfdook Zonuyp Nuloam (Egmewigji qinu) Jusioh (Vfzvnsudekefiem) Uititameq (Xaguiloroy)

Understanding the actor Keyword

To create a Swift actor, use the actor keyword:

Understanding @MainActor

The Swift Concurrency framework provides a special kind of actor, called MainActor. MainActor is global, and only one instance of it exists. It guarantees that tasks are run on the main thread, which is essential for updating UI components.

Trying out @MainActor

Let’s put @MainActor to use and see how it interacts with async functions.

Nlatxfuiyg Pistota Eondoh Ipog
Zranzrairz Camvuyo Iepgon Asir

Heaf Ohnag Xrogkfiiph
Buub Intor Qtivlxoapf

Update the Weather App

Launch the WeatherSampleApp project in Xcode and open the WeatherRepositoryImpl.swift file. Find the following line:

See forum comments
Download course materials from Github
Previous: Introduction Next: Conclusion