美文网首页
Swift 析构

Swift 析构

作者: 点滴86 | 来源:发表于2016-08-11 15:14 被阅读4次

析构

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

相关文章

网友评论

      本文标题:Swift 析构

      本文链接:https://www.haomeiwen.com/subject/nehssttx.html