0
0
Swiftprogramming~30 mins

Actor declaration syntax in Swift - Mini Project: Build & Apply

Choose your learning style9 modes available
Actor declaration syntax
📖 Scenario: Imagine you are building a simple app that manages a shared counter safely across multiple parts of your program. You want to use Swift's actor to protect the counter from being changed at the same time by different parts.
🎯 Goal: You will create an actor named Counter that holds a number and safely increases it. Then you will print the current value.
📋 What You'll Learn
Create an actor named Counter with a variable value initialized to 0
Add a function increment() inside the actor that increases value by 1
Create an instance of Counter named myCounter
Call increment() on myCounter and print the updated value
💡 Why This Matters
🌍 Real World
Actors are used in Swift apps to safely manage data that many parts of the app might want to change at the same time, like counters, user settings, or shared resources.
💼 Career
Understanding actors is important for Swift developers working on apps that use concurrency, such as iOS or macOS apps that need to be fast and safe.
Progress0 / 4 steps
1
Create an actor with a value variable
Write an actor named Counter that has a variable value set to 0 inside it.
Swift
Need a hint?

Use the keyword actor followed by the name Counter. Inside curly braces, declare var value = 0.

2
Add an increment function inside the actor
Inside the Counter actor, add a function named increment() that adds 1 to the value variable.
Swift
Need a hint?

Define a function increment() inside the actor that increases value by 1 using value += 1.

3
Create an instance of the actor
Create a constant named myCounter and set it to a new instance of the Counter actor.
Swift
Need a hint?

Use let myCounter = Counter() to create the actor instance.

4
Call increment and print the value
Call the increment() function on myCounter using await, then print the current value from myCounter also using await.
Swift
Need a hint?

Use await myCounter.increment() to call the function, then let currentValue = await myCounter.value to get the value, and finally print(currentValue).