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 0Add a method
increment() to increase value by 1Mark the
Counter class with the @MainActor attributeCreate an instance of
Counter and call increment() three timesPrint 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