Avatar
ありがとうございました〜〜〜! 私は最終的にこうなりました↓ <NSThread: 0x600003d4e1c0>{number = 6, name = (null)} <NSThread: 0x600003d3ae40>{number = 4, name = (null)} A: 100 A: 200 A: 300 A: 450 A: 350 A: 250 A:150 B: 100 A:150 B: 100 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 accountA = BankAccount() let accountB = BankAccount() Task.detached { print(Thread.current) print("A: \(await accountA.deposit(100))") print("A: \(await accountA.getInterest(with: 0.5))") print("A: \(try await accountA.withdraw(100))") try await accountA.transfer(50, to: accountB) print("A:\(await accountA.balance) B: \(await accountB.balance)") } Task { print(Thread.current) print("A: \(await accountA.deposit(100))") print("A: \(await accountA.getInterest(with: 0.5))") print("A: \(try await accountA.withdraw(100))") try await accountA.transfer(50, to: accountB) print("A:\(await accountA.balance) B: \(await accountB.balance)") } }