0
0
Swiftprogramming~30 mins

Nonisolated methods in Swift - Mini Project: Build & Apply

Choose your learning style9 modes available
Using Nonisolated Methods in Swift Actors
📖 Scenario: You are building a simple Swift program that uses an actor to manage a counter. You want to add a method that can be called without waiting for the actor's isolation, so it can be accessed quickly and safely from any thread.
🎯 Goal: Create an actor named Counter with a nonisolated method that returns a greeting message. This method should be callable without awaiting the actor.
📋 What You'll Learn
Create an actor named Counter with a variable count initialized to 0
Add a nonisolated method greeting() that returns the string "Hello from Counter!"
Add an isolated method increment() that increases count by 1
Print the result of calling greeting() without awaiting
Print the value of count after calling increment() with awaiting
💡 Why This Matters
🌍 Real World
Actors help manage data safely when multiple parts of a program run at the same time. Nonisolated methods let you quickly get information that doesn't change the data.
💼 Career
Understanding actors and nonisolated methods is important for writing safe and efficient Swift code in apps that use concurrency, such as iOS or macOS applications.
Progress0 / 4 steps
1
Create the Counter actor with a count variable
Create an actor named Counter with a variable count set to 0 inside it.
Swift
Need a hint?

Use the actor keyword to define Counter and add var count = 0 inside.

2
Add a nonisolated greeting() method
Inside the Counter actor, add a nonisolated method named greeting() that returns the string "Hello from Counter!".
Swift
Need a hint?

Use nonisolated func greeting() -> String and return the exact string.

3
Add an isolated increment() method
Inside the Counter actor, add a method named increment() that increases the count variable by 1.
Swift
Need a hint?

Define func increment() and add count += 1 inside.

4
Call greeting() and increment(), then print results
Create an instance of Counter named counter. Print the result of calling counter.greeting() without await. Then await counter.increment() and print the value of counter.count by awaiting a new method getCount() that returns count.
Swift
Need a hint?

Remember to add getCount() to return count. Use await when calling increment() and getCount(). Print the greeting without await.