Swift 析构

2016-08-11  本文已影响4人  点滴86

析构

import UIKit

class Bank {
    static var coinsInBank = 10_000
    static func distribute(numberOfCoinsRequested: Int) -> Int {
        let numberOfCoinsToVend = min(numberOfCoinsRequested, coinsInBank)
        coinsInBank -= numberOfCoinsToVend
        return numberOfCoinsToVend
    }
    
    static func receive(coins: Int) {
        coinsInBank += coins
    }
}

class Player {
    var coinsInpurse: Int
    init(coins: Int) {
        coinsInpurse = Bank.distribute(coins)
    }
    
    func win(coins: Int) {
        coinsInpurse += Bank.distribute(coins)
    }
    
    deinit {
        Bank.receive(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!.win(2_000)
print("PlayerOne won 2000 coins & now has \(playerOne!.coinsInpurse) coins")
print("The bank now only has \(Bank.coinsInBank) coins left")

playerOne = nil
print("PlayerOne has left the game")
print("The bank now has \(Bank.coinsInBank) coins")

console log 如下


析构.png
上一篇 下一篇

猜你喜欢

热点阅读