Bird
Raised Fist0
Swiftprogramming~10 mins

Actor declaration syntax in Swift - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Actor declaration syntax
Start
↓
Write 'actor' keyword
↓
Name the actor
↓
Add braces { }
↓
Declare properties and methods inside
↓
Actor ready to use
↓
End
This flow shows how to declare an actor in Swift: start with the 'actor' keyword, give it a name, add braces, then put properties and methods inside.
Execution Sample
Swift
actor Counter {
    var value = 0
    func increment() {
        value += 1
    }
}
Declares an actor named Counter with a value property and an increment method.
Execution Table
StepActionCode PartResult
1Read 'actor' keywordactorStart actor declaration
2Read actor nameCounterActor named 'Counter' created
3Open braces{Begin actor body
4Declare propertyvar value = 0Property 'value' initialized to 0
5Declare methodfunc increment() { value += 1 }Method 'increment' added
6Close braces}Actor declaration complete
💡 Actor declaration ends after closing brace '}'
Variable Tracker
VariableStartAfter Step 4After Step 5Final
valueundefined000
increment methodundefinedundefineddefineddefined
Key Moments - 3 Insights
Why do we use the 'actor' keyword instead of 'class'?
The 'actor' keyword defines a special type that protects its data from concurrent access, unlike 'class'. See execution_table step 1 where 'actor' starts this special declaration.
Can we declare properties inside the actor?
Yes, properties like 'value' are declared inside the braces as shown in execution_table step 4.
What does the method inside the actor do?
The method 'increment' changes the property 'value' safely inside the actor, as shown in execution_table step 5.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the actor's name at step 2?
Aincrement
Bvalue
CCounter
Dactor
💡 Hint
Check the 'Code Part' column at step 2 in execution_table.
At which step is the property 'value' initialized?
AStep 4
BStep 5
CStep 3
DStep 6
💡 Hint
Look for 'var value = 0' in the 'Code Part' column of execution_table.
If we remove the closing brace '}', what happens to the actor declaration?
AIt completes normally
BIt causes a syntax error
CThe actor name changes
DThe method is removed
💡 Hint
Refer to exit_note and step 6 in execution_table about the closing brace.
Concept Snapshot
Swift Actor Declaration Syntax:
- Use 'actor' keyword
- Name the actor (e.g., Counter)
- Use braces { } to hold properties and methods
- Properties and methods are isolated for safe concurrency
- Actor protects its data from concurrent access
Full Transcript
This visual execution shows how to declare an actor in Swift. First, the 'actor' keyword is read, starting the declaration. Then the actor is named, for example, 'Counter'. Next, braces are opened to hold the actor's body. Inside, properties like 'value' are declared and initialized. Methods like 'increment' are added to change properties safely. Finally, the closing brace ends the declaration. Actors are special types that protect their data from concurrent access, unlike classes. This step-by-step trace helps beginners see how each part of the actor declaration builds up.

Practice

(1/5)
1. What keyword is used to declare an actor in Swift?
easy
A. class
B. enum
C. struct
D. actor

Solution

  1. Step 1: Understand actor declaration

    Actors in Swift are declared using a special keyword to indicate their concurrency-safe nature.
  2. Step 2: Identify the correct keyword

    The keyword actor is used to declare actors, differentiating them from classes, structs, or enums.
  3. Final Answer:

    actor -> Option D
  4. Quick Check:

    Actor declaration keyword = actor [OK]
Hint: Actors always start with the keyword 'actor' [OK]
Common Mistakes:
  • Using class instead of actor
  • Confusing struct with actor
  • Trying to declare actor with enum
2. Which of the following is the correct syntax to declare an actor named DataManager?
easy
A. actor DataManager() { }
B. actor DataManager { }
C. struct DataManager { }
D. class DataManager { }

Solution

  1. Step 1: Recall actor declaration syntax

    Actors are declared with the keyword actor followed by the name and curly braces without parentheses.
  2. Step 2: Check each option

    actor DataManager { } uses correct syntax: actor DataManager { }. actor DataManager() { } incorrectly adds parentheses after the name.
  3. Final Answer:

    actor DataManager { } -> Option B
  4. Quick Check:

    Correct actor syntax = actor Name { } [OK]
Hint: Actors do not use parentheses after their name [OK]
Common Mistakes:
  • Adding parentheses after actor name
  • Using class or struct instead of actor
  • Omitting curly braces
3. What will be the output of the following Swift code?
actor Counter {
    var value = 0
    func increment() {
        value += 1
    }
}

let counter = Counter()
Task {
    await counter.increment()
    print(await counter.value)
}
medium
A. 1
B. 0
C. Compilation error
D. Runtime error

Solution

  1. Step 1: Understand actor behavior and method calls

    The actor Counter has a variable value initialized to 0 and a method increment() that adds 1 to value. The method is called with await inside a Task.
  2. Step 2: Trace the code execution

    The increment() method increases value from 0 to 1. Then print(await counter.value) prints the updated value, which is 1.
  3. Final Answer:

    1 -> Option A
  4. Quick Check:

    Incremented value = 1 [OK]
Hint: Remember to await actor method calls and property access [OK]
Common Mistakes:
  • Forgetting to use await with actor calls
  • Expecting initial value 0 after increment
  • Assuming synchronous access to actor properties
4. Identify the error in the following actor declaration and fix it:
actor Logger {
    var logs: [String]
    func addLog(_ message: String) {
        logs.append(message)
    }
}
medium
A. Missing initialization of 'logs' array
B. Actor cannot have functions
C. Use 'class' instead of 'actor'
D. Missing 'await' keyword in function

Solution

  1. Step 1: Check property initialization in actor

    The property logs is declared but not initialized. In Swift, stored properties must have initial values or be initialized in an initializer.
  2. Step 2: Identify the fix

    Initialize logs as an empty array: var logs: [String] = [] to fix the error.
  3. Final Answer:

    Missing initialization of 'logs' array -> Option A
  4. Quick Check:

    Stored properties need initial values [OK]
Hint: Always initialize stored properties in actors [OK]
Common Mistakes:
  • Assuming default initialization for arrays
  • Thinking actors cannot have functions
  • Forgetting to add await when calling actor methods
5. You want to create an actor BankAccount that safely manages a balance. Which of the following code snippets correctly declares the actor and provides a method to deposit money asynchronously?
hard
A. actor BankAccount { var balance: Double = 0.0 func deposit(amount: Double) { balance += amount } }
B. actor BankAccount { var balance: Double = 0.0 func deposit(amount: Double) { await balance += amount } }
C. actor BankAccount { var balance: Double = 0.0 func deposit(amount: Double) async { await Task.sleep(1_000_000_000) balance += amount } }
D. class BankAccount { var balance: Double = 0.0 func deposit(amount: Double) async { balance += amount } }

Solution

  1. Step 1: Understand actor method concurrency

    Actor methods that perform asynchronous work should be marked async. actor BankAccount { var balance: Double = 0.0 func deposit(amount: Double) { balance += amount } } lacks async on the method, so it cannot await inside.
  2. 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 } } marks deposit as async and simulates asynchronous delay with await Task.sleep(), showing proper async usage inside an actor.
  3. Step 3: Verify actor declaration

    class BankAccount { var balance: Double = 0.0 func deposit(amount: Double) async { balance += amount } } uses class instead of actor, so it does not provide concurrency safety.
  4. Final Answer:

    correctly declares an actor with an async deposit method including await -> Option C
  5. Quick 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]
Hint: Async actor methods must be marked async and use await inside [OK]
Common Mistakes:
  • Omitting async keyword on async actor methods
  • Using class instead of actor for concurrency
  • Not using await inside async methods when needed
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard