Avatar
Q5 の回答 <NSThread: 0x6000024e8680>{number = 6, name = (null)} <NSThread: 0x6000024d4240>{number = 7, name = (null)} 100 200 300 450 250 50 import Foundation struct AccountError: Error { } actor BankAccount { var balance = 0 func deposit(_ amount: Int) -> Int { balance += amount Thread.sleep(forTimeInterval: 1.0) return balance } func getInterest(with rate: Double) -> Int { deposit(Int(Double(balance) * rate)) } func withdraw(_ amount: Int) throws -> Int { let newBalance = balance - amount guard newBalance >= 0 else { throw AccountError() } return deposit(-amount) } func transfer(_ amount: Int, to account: BankAccount) async throws { let newBalance = balance - amount guard newBalance >= 0 else { throw AccountError() } _ = deposit(-amount) _ = await account.deposit(amount) } } func bankAccountMain() { let bankAccount = BankAccount() Task.detached { print(Thread.current) print(await bankAccount.deposit(100)) print(await bankAccount.getInterest(with: 0.5)) print(try await bankAccount.withdraw(200)) } Task { print(Thread.current) print(await bankAccount.deposit(100)) print(await bankAccount.getInterest(with: 0.5)) print(try await bankAccount.withdraw(200)) } } (edited)