0
0
Swiftprogramming~30 mins

Actors vs locks decision in Swift - Hands-On Comparison

Choose your learning style9 modes available
Actors vs Locks Decision in Swift
📖 Scenario: You are building a simple bank account system where multiple parts of your app can deposit and withdraw money. You want to keep the balance safe from mistakes when many parts try to change it at the same time.
🎯 Goal: Learn how to use actor and lock to protect shared data and decide which one to use.
📋 What You'll Learn
Create a class BankAccountWithLock that uses a lock to protect the balance
Create an actor called BankAccountActor that protects the balance automatically
Write code to deposit and withdraw money safely in both versions
Print the final balances from both versions to compare
💡 Why This Matters
🌍 Real World
Banking apps, games, or any app where multiple parts change shared data at the same time.
💼 Career
Understanding concurrency safety is key for writing reliable Swift apps, especially with Swift's new actor model.
Progress0 / 4 steps
1
Create BankAccountWithLock class with balance and lock
Create a class called BankAccountWithLock with a balance property set to 0. Add a NSLock property called lock to protect the balance.
Swift
Need a hint?

Use NSLock() to create the lock. Keep balance private.

2
Add deposit and withdraw methods with lock
Add two methods to BankAccountWithLock: deposit(amount: Int) and withdraw(amount: Int). Use lock.lock() before changing balance and lock.unlock() after.
Swift
Need a hint?

Remember to lock before changing balance and unlock after.

3
Create BankAccountActor with async deposit and withdraw
Create an actor called BankAccountActor with a balance property set to 0. Add async methods deposit(amount: Int) and withdraw(amount: Int) that update balance safely.
Swift
Need a hint?

Actors protect data automatically, so no locks needed inside.

4
Use both accounts and print final balances
Create an instance of BankAccountWithLock called lockedAccount and an instance of BankAccountActor called actorAccount. Deposit 100 and withdraw 40 on both. Print the final balances for both accounts.
Swift
Need a hint?

Use Task to call async methods on the actor. Add getBalance() methods to read balances.