Actor declaration syntax in Swift - Time & Space Complexity
When we declare an actor in Swift, it helps manage tasks safely across threads.
We want to see how the time to create or use an actor changes as the program grows.
Analyze the time complexity of the following actor declaration and usage.
actor Counter {
var value = 0
func increment() {
value += 1
}
}
let counter = Counter()
await counter.increment()
This code declares an actor with a simple counter and increments its value once.
Look for repeated actions or loops that take time.
- Primary operation: Calling the increment() method once on the actor.
- How many times: Exactly one time in this example.
Since the actor method is called only once, the time grows very little as input grows.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 1 |
| 100 | 1 |
| 1000 | 1 |
Pattern observation: The time stays the same no matter how big the input is.
Time Complexity: O(1)
This means the time to call the actor method does not grow with input size; it stays constant.
[X] Wrong: "Calling a method on an actor takes longer as the program gets bigger."
[OK] Correct: Each actor method call runs independently and does not slow down just because the program has more code or data.
Understanding how actor calls behave helps you write safe and efficient code that works well with Swift concurrency.
"What if the increment() method contained a loop that ran n times? How would the time complexity change?"
Practice
Solution
Step 1: Understand actor declaration
Actors in Swift are declared using a special keyword to indicate their concurrency-safe nature.Step 2: Identify the correct keyword
The keywordactoris used to declare actors, differentiating them from classes, structs, or enums.Final Answer:
actor -> Option DQuick Check:
Actor declaration keyword = actor [OK]
- Using class instead of actor
- Confusing struct with actor
- Trying to declare actor with enum
DataManager?Solution
Step 1: Recall actor declaration syntax
Actors are declared with the keywordactorfollowed by the name and curly braces without parentheses.Step 2: Check each option
actor DataManager { } uses correct syntax:actor DataManager { }. actor DataManager() { } incorrectly adds parentheses after the name.Final Answer:
actor DataManager { } -> Option BQuick Check:
Correct actor syntax = actor Name { } [OK]
- Adding parentheses after actor name
- Using class or struct instead of actor
- Omitting curly braces
actor Counter {
var value = 0
func increment() {
value += 1
}
}
let counter = Counter()
Task {
await counter.increment()
print(await counter.value)
}Solution
Step 1: Understand actor behavior and method calls
The actorCounterhas a variablevalueinitialized to 0 and a methodincrement()that adds 1 tovalue. The method is called withawaitinside a Task.Step 2: Trace the code execution
Theincrement()method increasesvaluefrom 0 to 1. Thenprint(await counter.value)prints the updated value, which is 1.Final Answer:
1 -> Option AQuick Check:
Incremented value = 1 [OK]
- Forgetting to use await with actor calls
- Expecting initial value 0 after increment
- Assuming synchronous access to actor properties
actor Logger {
var logs: [String]
func addLog(_ message: String) {
logs.append(message)
}
}Solution
Step 1: Check property initialization in actor
The propertylogsis declared but not initialized. In Swift, stored properties must have initial values or be initialized in an initializer.Step 2: Identify the fix
Initializelogsas an empty array:var logs: [String] = []to fix the error.Final Answer:
Missing initialization of 'logs' array -> Option AQuick Check:
Stored properties need initial values [OK]
- Assuming default initialization for arrays
- Thinking actors cannot have functions
- Forgetting to add await when calling actor methods
BankAccount that safely manages a balance. Which of the following code snippets correctly declares the actor and provides a method to deposit money asynchronously?Solution
Step 1: Understand actor method concurrency
Actor methods that perform asynchronous work should be markedasync. actor BankAccount { var balance: Double = 0.0 func deposit(amount: Double) { balance += amount } } lacksasyncon the method, so it cannot await inside.Step 2: Check for realistic async behavior
actor BankAccount { var balance: Double = 0.0 func deposit(amount: Double) async { await Task.sleep(1_000_000_000) balance += amount } } marksdepositasasyncand simulates asynchronous delay withawait Task.sleep(), showing proper async usage inside an actor.Step 3: Verify actor declaration
class BankAccount { var balance: Double = 0.0 func deposit(amount: Double) async { balance += amount } } usesclassinstead ofactor, so it does not provide concurrency safety.Final Answer:
correctly declares an actor with an async deposit method including await -> Option CQuick Check:
Actor + async method + await inside = actor BankAccount { var balance: Double = 0.0 func deposit(amount: Double) async { await Task.sleep(1_000_000_000) balance += amount } } [OK]
- Omitting async keyword on async actor methods
- Using class instead of actor for concurrency
- Not using await inside async methods when needed
Ready to prove it?
Pass the test and this pattern moves unknown
