struct Bank {
static var coinsInBank = 10000;
static func vendCoins(var numberOfCoinsToVend: Int) -> Int {
numberOfCoinsToVend = min(numberOfCoinsToVend, coinsInBank);
coinsInBank -= numberOfCoinsToVend;
return numberOfCoinsToVend;
}
static func receiveCoins(coins: Int) {
coinsInBank += coins;
}
}
class Player {
var coinsInPurse: Int;
init(coins: Int) {
coinsInPurse = Bank.vendCoins(coins);
}
func winCoins(coins: Int) {
coinsInPurse += Bank.vendCoins(coins);
}
deinit {//有點像OC中的dealloc
Bank.receiveCoins(coinsInPurse);
}
}
var playerOne: Player? = Player(coins: 100);
print("A new player has joined the game with \(playerOne!.coinsInPurse) coins");
print("There are now \(Bank.coinsInBank) coins left in the bank");
playerOne!.winCoins(2000);
print("playerOne won 2000 coins & now has \(playerOne!.coinsInPurse) coins");
print("There are now \(Bank.coinsInBank) coins left in the bank");
playerOne = nil;
print("There are now \(Bank.coinsInBank) coins left in the bank");