swft deinit

swift deinit

/*

    deinit only for class

    by Default the ARC(automatic reference counting) manage your deinit

    but sometimes for example you want to close a file writing process first

 */


class CoinBank{

    static var CoinDeposit = 1000

    static func distribute(Coin:Int)->Int{

        if Coin > CoinDeposit {

            print("Don't have enough Coin in Coin bank, return\(CoinDeposit)")

            return CoinDeposit

        }else{

            CoinDeposit -= Coin

            return Coin

        }

    }

    static func receive(Coin:Int)->Int{

        CoinDeposit += Coin

        if CoinDeposit > 1000{

            print("Coin bank exceeds deposit limit, force remove the surplus amount")

            CoinDeposit = 1000

            return CoinDeposit

        }else{

            return CoinDeposit

        }

    }

}


class Player{

    var CoinInPurse:Int

    init(Coin:Int){

        CoinInPurse=CoinBank.distribute(Coin: Coin)

    }

    func win(WinCoin:Int)->Int{

        CoinInPurse += WinCoin

        return WinCoin

    }

    func lose(LoseCoin:Int)->Int{

        CoinInPurse -= LoseCoin

        return LoseCoin

    }

    deinit{

        CoinBank.receive(Coin: CoinInPurse)

    }

}


var PlayerA = Player(Coin: 100)


print(CoinBank.CoinDeposit)


var PlayerB:Player? = Player(Coin:500)


print(CoinBank.CoinDeposit)


PlayerB!.win(WinCoin: 1000)


print(CoinBank.CoinDeposit)


PlayerB = nil





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值