反初始化函数

//: Playground - noun: a place where people can play

import UIKit

//这里是一个反初始化函数操作的例子。

struct Bank {

    static var coinsInBank = 10_000

    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 {

        Bank.receiveCoins(coinsInPurse)

    }

}

var playerOne: Player? = Player(coins: 100)

playerOne?.coinsInPurse

Bank.coinsInBank


playerOne?.winCoins(2_000)

playerOne?.coinsInPurse

Bank.coinsInBank

playerOne = nil

Bank.coinsInBank


你可能感兴趣的:(Swift,反初始化函数,Swift)