0
0
Swiftprogramming~30 mins

Global actors (@MainActor) in Swift - Mini Project: Build & Apply

Choose your learning style9 modes available
Using Global Actors with @MainActor in Swift
📖 Scenario: You are building a simple Swift program that manages a shared counter. This counter must be updated safely on the main thread to avoid conflicts in a user interface environment.
🎯 Goal: Learn how to use the @MainActor global actor to ensure that updates to a shared resource happen on the main thread.
📋 What You'll Learn
Create a class called Counter with a property value initialized to 0
Add a method increment() to increase value by 1
Mark the Counter class with the @MainActor attribute
Create an instance of Counter and call increment() three times
Print the final value of the counter
💡 Why This Matters
🌍 Real World
In apps with user interfaces, updating shared data on the main thread prevents crashes and keeps UI smooth.
💼 Career
Understanding @MainActor is important for Swift developers working on iOS/macOS apps to write safe, concurrent code.
Progress0 / 4 steps
1
Create the Counter class
Create a class called Counter with a property value set to 0.
Swift
Need a hint?

Use class Counter { var value = 0 } to define the class and property.

2
Add increment() method
Add a method called increment() inside the Counter class that increases value by 1.
Swift
Need a hint?

Define func increment() { value += 1 } inside the class.

3
Mark Counter with @MainActor
Add the @MainActor attribute before the Counter class declaration to make it a global actor isolated class.
Swift
Need a hint?

Place @MainActor on the line above class Counter.

4
Use Counter and print value
Create an instance of Counter called counter. Call increment() three times on counter. Then print counter.value.
Swift
Need a hint?

Use let counter = Counter(), call counter.increment() three times, then print(counter.value).