Skip to content

Commit 3f9934a

Browse files
added actor example
1 parent 4da357e commit 3f9934a

1 file changed

Lines changed: 28 additions & 0 deletions

File tree

SwiftUIExamples/SwiftUI-CommandLineTool/main.swift

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -283,3 +283,31 @@ func exampleOfClassWithSendableProperties() {
283283
exampleOfClassWithSendableProperties()
284284
// Use @concurrent to run on background thread. example fetchImage and decode image. for display Image use @mainactor
285285
// preconcurrency to silence the warning
286+
// MARK: - actor example
287+
//Isolation: Actors run in their own independent domain. Access to their properties is serialized, which means only one task can interact with an actor's state at one time.
288+
// Define an actor
289+
actor BankAccount {
290+
var balance: Double = 0.0
291+
292+
func deposit(amount: Double) {
293+
balance += amount
294+
}
295+
296+
func withdraw(amount: Double) {
297+
balance -= amount
298+
}
299+
300+
func getBalance() -> Double {
301+
return balance
302+
}
303+
}
304+
305+
// Using the actor
306+
func performTransactions() async {
307+
let account = BankAccount()
308+
await account.deposit(amount: 100.0) // Asynchronous call
309+
await account.withdraw(amount: 10) // Asynchronous call
310+
let currentBalance = await account.getBalance() // Asynchronous call
311+
print("Current balance: \(currentBalance)")
312+
}
313+
await performTransactions()

0 commit comments

Comments
 (0)