ARTICLE AD BOX
In the code below I have the actor BankAccount and the non-sendable type AlternativeBankAccount. Both have the same body.
I cannot understand why the compiler does not trigger a warning when passing an AlternativeBankAccount to the charge function. The asynchronous context changes from the body of random to the charge and I thought this would force sendable conformance to all parameters of charge .
If someone can explain me I would be very happy! Thanks in advance!
Logs:
1 - <_NSMainThread: 0x600001704040>{number = 1, name = main} 2 - <NSThread: 0x600001711100>{number = 7, name = (null)}Code:
actor BankAccount { enum BankError: Error { case insufficientFunds } var balance: Double init(initialDeposit: Double) { self.balance = initialDeposit } func withdraw(amount: Double) throws { guard balance >= amount else { throw BankError.insufficientFunds } balance -= amount } func deposit(amount: Double) { balance += amount } } class AlternativeBankAccount { enum BankError: Error { case insufficientFunds } var balance: Double init(initialDeposit: Double) { self.balance = initialDeposit } func withdraw(amount: Double) throws { guard balance >= amount else { throw BankError.insufficientFunds } balance -= amount } func deposit(amount: Double) { balance += amount } } struct Charger { func charge(amount: Double, from bankAccount: isolated BankAccount, to otherAccount: AlternativeBankAccount) async throws -> (Double, Double) { print("2 - \(Thread.currentThread)") try bankAccount.withdraw(amount: amount) let newBalance = bankAccount.balance otherAccount.deposit(amount: amount) return (newBalance, otherAccount.balance) } } @MainActor class ViewModel { let charger = Charger() func random(bankAccount: BankAccount) { let bankAccount2 = AlternativeBankAccount(initialDeposit: 200) Task { print("1 - \(Thread.currentThread)") let aa = try? await charger.charge(amount: 100, from: bankAccount, to: bankAccount2) print("balance", aa?.0 ?? "", aa?.1 ?? "") } } }1,3971 gold badge16 silver badges26 bronze badges
