Avatar
できた(ネタバレ注意) import Foundation struct WithdrawError: 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 { precondition(amount > 0) guard balance - amount >= 0 else { throw WithdrawError() } balance -= amount Thread.sleep(forTimeInterval: 1.0) return balance } func transfer(_ amount: Int, to account: BankAccount) async throws { _ = try withdraw(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)) } }