0
0
Swiftprogramming~5 mins

Actor declaration syntax in Swift - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is the basic syntax to declare an actor in Swift?
Use the keyword actor followed by the actor's name and curly braces. For example:<br>
actor MyActor {
    // actor code here
}
Click to reveal answer
beginner
Can an actor in Swift have properties and methods?
Yes, actors can have properties and methods just like classes. These help manage state safely in concurrent code.
Click to reveal answer
intermediate
How do you mark a method inside an actor as asynchronous?
You add the async keyword after the method's parameter list and before the return type. For example:<br>
func fetchData() async -> String {
    // code
}
Click to reveal answer
intermediate
Why use actors instead of classes for concurrency in Swift?
Actors protect their internal state by serializing access, preventing data races in concurrent environments.
Click to reveal answer
beginner
How do you create an instance of an actor?
You create it like a class instance using the initializer:<br><pre>let myActor = MyActor()</pre>
Click to reveal answer
Which keyword is used to declare an actor in Swift?
Aactor
Bclass
Cstruct
Denum
What is the main benefit of using actors in Swift?
AThey serialize access to their internal state to prevent data races.
BThey allow multiple threads to access state simultaneously.
CThey replace functions with asynchronous calls.
DThey automatically optimize memory usage.
How do you mark a method inside an actor as asynchronous?
ANo special keyword is needed.
BAdd the <code>async</code> keyword before the return type.
CUse the <code>async</code> keyword after the method name.
DAdd the <code>await</code> keyword before the method name.
How do you create an instance of an actor named DataManager?
Anew DataManager()
Bactor dm = DataManager()
Clet dm = actor DataManager()
Dlet dm = DataManager()
Can actors in Swift have stored properties?
ANo, actors cannot have any properties.
BNo, actors can only have computed properties.
CYes, actors can have stored properties.
DOnly static properties are allowed.
Explain how to declare an actor in Swift and why you would use one.
Think about how actors help with safe access to data when many things happen at once.
You got /4 concepts.
    Describe how asynchronous methods work inside an actor and how you declare them.
    Remember that async methods let you wait for work without blocking the whole program.
    You got /4 concepts.