Actor isolation helps keep data safe when many parts of a program work at the same time. It makes sure only one part can change data at once.
0
0
Actor isolation concept in Swift
Introduction
When you have a program with many tasks running at the same time and want to avoid mistakes.
When you want to protect important data from being changed by accident.
When you want to organize your code so that only certain parts can access or change data.
When you want to avoid confusing bugs caused by multiple parts changing data together.
Syntax
Swift
actor MyActor {
var count = 0
func increment() {
count += 1
}
}An actor is like a safe box that controls access to its data.
Only one task can use the actor's data at a time, preventing conflicts.
Examples
This actor holds a number and has a function to add one to it safely.
Swift
actor Counter {
var value = 0
func increase() {
value += 1
}
}When calling an actor's function from outside, use
await to wait safely.Swift
let counter = Counter() Task { await counter.increase() }
Sample Program
This program creates a BankAccount actor that safely manages money. It deposits and withdraws money one at a time, printing the results.
Swift
import Foundation actor BankAccount { var balance: Int = 0 func deposit(amount: Int) { balance += amount print("Deposited \(amount), new balance: \(balance)") } func withdraw(amount: Int) { if balance >= amount { balance -= amount print("Withdrew \(amount), new balance: \(balance)") } else { print("Not enough balance to withdraw \(amount)") } } } let account = BankAccount() Task { await account.deposit(amount: 100) await account.withdraw(amount: 50) await account.withdraw(amount: 100) } // Keep the program running to see async prints RunLoop.main.run(until: Date().addingTimeInterval(1))
OutputSuccess
Important Notes
Use await when calling actor methods from outside to wait for safe access.
Actors help avoid bugs caused by multiple parts changing data at the same time.
Inside the actor, you can access data directly without await.
Summary
Actors keep data safe by allowing only one task to access it at a time.
Use await to call actor methods from outside.
Actor isolation helps prevent bugs in programs that do many things at once.